import { TenantKind } from '@prisma/client';

/**
 * What kind of place a tenant is, and which parts of the product that kind
 * gets. Today every kind gets everything: the kind is recorded at sign-up so
 * the apps can start showing and hiding modules later without a data change,
 * and so an older app build, which does not know the field, keeps working.
 *
 * To switch a module off for a kind, set it to false here; `featuresFor`
 * feeds `/api/features` and the signed-in user's `features` list, and the
 * clients hide the matching navigation. Server-side gating goes through
 * `requireFeature` in the route that owns the module.
 */
export const FEATURE_KEYS = [
  'rooms', // properties, floors, rooms and beds
  'students', // residents, onboarding, KYC
  'billing', // rent and other invoices, receipts, billing rules
  'onlinePayments', // Razorpay links, virtual accounts, collections dashboard
  'moveOuts', // notice, settlement, refunds, asset checklist
  'mess', // menu, calendar, subscriptions, mess billing, opt-out, store
  'requests', // student requests, SLAs, vendors
  'gate', // passes, guard screen, attendance, visitors
  'guardians', // guardian logins and approvals
  'notices',
  'expenses', // expenses, P&L, salaries, Tally export
  'staff', // staff accounts and custom roles
  'biometric', // devices and punches
  'analytics',
  'publicPage', // vacancy page and enquiries
  // Enterprise suite, from here down: on for ENTERPRISE tenants only.
  'assignments', // hand a request to a member of staff; their own task list
  'attachments', // photos and documents on records
  'inbox', // in-app notification inbox
  'anonymousRequests', // employees may raise a complaint without their name
  'reports', // Excel reports and scheduled report emails
  // Sprint 1 (TEPL)
  'employeeRecords', // TEPL ID, card, department, contractor, shift; arrival check-in on first punch; departments
  'leavePolicy', // leave types, balances, hostel-then-plant approval, leave calendar
  'shiftRoster', // shifts, daily roster import, shift adherence
  // Sprint 2 (TEPL)
  'discipline', // incident register, repeat offences, discipline report
  'grievanceDesk', // complaint sub-categories, escalation when overdue, closure alerts, rating, grievance report
  'feedback', // monthly area ratings (anonymous allowed), trends and themes for HR
  'parcels', // parcels logged at the gate, collected by the employee
  'emergencyContacts', // shift-wise emergency directory, on duty now
  'lostFound', // found items, lost reports, claims
  // Sprint 3 (TEPL)
  'cleaning', // cleaning areas, rota, daily tasks with photos, missed-task alerts
  'roomInventory', // live room register, audits, work orders, general store
  'laundry', // laundry bags, vendor batches, tracking
  'staffAttendance', // staff clock-in/out (app or terminal), duty shifts, hours
  'energy', // energy meters and readings from the BMS
  // Sprint 4 (TEPL)
  'quickOutings', // outing passes without a leave request; terminal swipes move passes; curfew breaches
  'noticeTargeting', // notices to a block, floor, shift or department; read acknowledgement; WhatsApp broadcasts
  'busLog', // vehicles and the gate's trip log
  'visitorReports', // daily visitor report, most-visited employees
  // Sprint 5 (TEPL)
  'events', // events calendar, registration, attendance, feedback
  'emergency', // emergency broadcast, headcount, emergency team, drills
  'canteen', // meal windows, diets and diet menus, per-meal consumption, ratings, vendor swipe feed
  // Sprint 6 (TEPL)
  'medical', // OHC medical records, visits, appointments; sealed, logged, OHC only
  'specialNeeds', // accessibility profiles, accessible rooms and beds, assistance requests
  'leadership', // leadership dashboard across blocks
  'hrFeeds', // TEPL roster and plant-leave feeds
  // Sprint 7 (TEPL)
  'compliance', // licences, permits, registers, inspections and findings, with reminders and an audit trail
] as const;

export type FeatureKey = (typeof FEATURE_KEYS)[number];

export const TENANT_KIND_LABELS: Record<TenantKind, string> = {
  HOSTEL: 'Hostel',
  PG: 'PG / co-living',
  DORMITORY: 'Dormitory',
  ENTERPRISE: 'Enterprise',
};

const everything = (): Record<FeatureKey, boolean> => Object.fromEntries(FEATURE_KEYS.map((k) => [k, true])) as Record<FeatureKey, boolean>;

/**
 * The enterprise suite. These modules stay off for every other kind, so
 * hostels, PGs and dormitories see nothing new.
 */
export const ENTERPRISE_SUITE: FeatureKey[] = [
  'assignments',
  'attachments',
  'inbox',
  'anonymousRequests',
  'reports',
  'employeeRecords',
  'leavePolicy',
  'shiftRoster',
  'discipline',
  'grievanceDesk',
  'feedback',
  'parcels',
  'emergencyContacts',
  'lostFound',
  'cleaning',
  'roomInventory',
  'laundry',
  'staffAttendance',
  'energy',
  'quickOutings',
  'noticeTargeting',
  'busLog',
  'visitorReports',
  'events',
  'emergency',
  'canteen',
  'medical',
  'specialNeeds',
  'leadership',
  'hrFeeds',
  'compliance',
];
const withoutSuite = (table: Record<FeatureKey, boolean>): Record<FeatureKey, boolean> => ({
  ...table,
  ...Object.fromEntries(ENTERPRISE_SUITE.map((k) => [k, false])),
});

/**
 * Per kind, which modules are on. Hostels and PGs get everything. A
 * dormitory turns over beds by the night or the hour, so notice periods and
 * settlements, gate passes, the mess and notice boards do not apply there
 * (owner's decision, 5 Oct 2026); the clients hide those entries.
 */
export const FEATURES_BY_KIND: Record<TenantKind, Record<FeatureKey, boolean>> = {
  HOSTEL: withoutSuite(everything()),
  PG: withoutSuite(everything()),
  DORMITORY: withoutSuite({ ...everything(), moveOuts: false, gate: false, mess: false, notices: false }),
  // A company hostel runs like a hostel: leave and outings at the gate,
  // the mess, notices, roll call — with employees instead of students. The
  // company pays, so nobody is billed, and there are no parents to approve.
  // No role sees money here (owner's rule, 6 Nov 2026), so the operator's own
  // books are off too: expenses, P&L, salaries, store and repair costs.
  ENTERPRISE: { ...everything(), billing: false, onlinePayments: false, publicPage: false, guardians: false, expenses: false },
};

/** The enabled feature keys for a kind, in catalogue order. */
export function featuresFor(kind: TenantKind | null | undefined): FeatureKey[] {
  const table = FEATURES_BY_KIND[kind ?? TenantKind.HOSTEL];
  return FEATURE_KEYS.filter((k) => table[k]);
}

export function hasFeature(kind: TenantKind | null | undefined, key: FeatureKey): boolean {
  return FEATURES_BY_KIND[kind ?? TenantKind.HOSTEL][key];
}
