import { Role } from '@prisma/client';
import type { FeatureKey } from './tenant-features';

/**
 * Granular permission catalog. Custom roles (per tenant) grant any subset of
 * these; base roles map to sensible defaults below. Fine-grained route guards
 * check these instead of (or in addition to) the coarse base role.
 */
export const PERMISSIONS = [
  'MANAGE_STAFF', // create sub-admins + custom roles + assign roles
  'MANAGE_PROPERTY', // properties setup
  'MANAGE_ROOMS', // rooms & beds
  'MANAGE_STUDENTS', // onboard / assign students
  'VIEW_OCCUPANCY',
  'MANAGE_RENT', // set rent, generate invoices, record payments
  'MANAGE_EXPENSES',
  'MANAGE_MESS', // menu + fee
  'POST_NOTICES',
  'VIEW_ANALYTICS',
  'MANAGE_DEVICES', // biometric terminals
  'MANAGE_GATE', // passes, gate scans, visitors
  'VIEW_ATTENDANCE', // who is in, attendance strips
  // Sprint 0 (TEPL): housekeeping and maintenance staff on their own logins —
  // see and work the requests handed to them, nothing else.
  'WORK_TASKS',
  // Sprint 1 (TEPL): a plant manager deciding the plant step of a leave, for
  // the departments they approve — nothing else in the hostel.
  'APPROVE_PLANT_LEAVE',
  // Sprint 3 (TEPL): the housekeeping supervisor — cleaning rota and tasks, laundry desk.
  'MANAGE_HOUSEKEEPING',
  // Sprint 5 (TEPL): the events calendar, and the emergency desk (alerts, team, drills).
  'MANAGE_EVENTS',
  'MANAGE_EMERGENCY',
  // Sprint 6 (TEPL): the OHC (medical records — never the owner's by default), and the leadership view.
  'MANAGE_MEDICAL',
  'VIEW_LEADERSHIP',
  // Sprint 7 (TEPL): statutory compliance — keep the records, or only read them.
  'MANAGE_COMPLIANCE',
  'VIEW_COMPLIANCE',
] as const;

export type Permission = (typeof PERMISSIONS)[number];

/**
 * Permissions that belong to a switchable module. The role editor offers
 * them only where the module is on, so a hostel never sees a box for a
 * module it does not have.
 */
export const PERMISSION_FEATURE: Partial<Record<Permission, FeatureKey>> = {
  MANAGE_EXPENSES: 'expenses',
  WORK_TASKS: 'assignments',
  APPROVE_PLANT_LEAVE: 'leavePolicy',
  MANAGE_HOUSEKEEPING: 'cleaning',
  MANAGE_EVENTS: 'events',
  MANAGE_EMERGENCY: 'emergency',
  MANAGE_MEDICAL: 'medical',
  VIEW_LEADERSHIP: 'leadership',
  MANAGE_COMPLIANCE: 'compliance',
  VIEW_COMPLIANCE: 'compliance',
};

const ALL: Permission[] = [...PERMISSIONS];

/**
 * Default permission set per base role (used when no custom role is assigned).
 * SUPER_ADMIN has NO tenant permissions — they manage the platform (tenants),
 * not tenant-internal resources — so tenant routes cleanly deny them.
 */
export const DEFAULT_PERMISSIONS: Record<Role, Permission[]> = {
  SUPER_ADMIN: [],
  HOSTEL_ADMIN: ALL, // owner of the tenant — full access, not restrictable
  WARDEN: ['MANAGE_ROOMS', 'MANAGE_STUDENTS', 'VIEW_OCCUPANCY', 'MANAGE_EXPENSES', 'POST_NOTICES', 'MANAGE_DEVICES', 'MANAGE_GATE', 'VIEW_ATTENDANCE'],
  MESS_ADMIN: ['MANAGE_MESS', 'POST_NOTICES'],
  STUDENT: [],
  // A guard has one job; a guardian reads through their own endpoints.
  GUARD: ['MANAGE_GATE'],
  GUARDIAN: [],
  // The platform's sales team: no hostel data at all, only /api/crm.
  CRM_USER: [],
  // The website's blog writers: no hostel data at all, only /api/blog-cms.
  CONTENT_EDITOR: [],
  // The bug tracker's testers and developers: only /api/bug-tracker.
  QA: [],
  DEVELOPER: [],
};

/**
 * Effective permissions for a user. HOSTEL_ADMIN always has all (can't be
 * locked out of their own tenant); WARDEN/MESS_ADMIN use their custom role's
 * permissions when assigned, else the base-role default.
 */
export function effectivePermissions(role: Role, customRolePermissions?: string[] | null): Permission[] {
  if (role === Role.HOSTEL_ADMIN) return ALL;
  if ((role === Role.WARDEN || role === Role.MESS_ADMIN) && customRolePermissions) {
    return customRolePermissions.filter((p): p is Permission => (PERMISSIONS as readonly string[]).includes(p));
  }
  return DEFAULT_PERMISSIONS[role];
}

/**
 * Platform team accounts with no tenant (the CRM's users, the blog's editors,
 * the bug tracker's testers and developers): always a second sign-in step,
 * which they cannot switch off, and an email only the super admin can change,
 * because their sign-in codes go there.
 */
export function alwaysTwoStep(role: Role): boolean {
  return role === 'CRM_USER' || role === 'CONTENT_EDITOR' || role === 'QA' || role === 'DEVELOPER';
}
