import { PrismaClient } from '@prisma/client';
import { getTenantContext } from './tenantContext';

/**
 * ─────────────────────────────────────────────────────────────────────────
 * Centralized tenant-scoping layer  (Sprint 1, task #2)
 * ─────────────────────────────────────────────────────────────────────────
 * Cross-tenant data leakage is the highest-severity bug class in this product.
 * We defend against it ONCE, here, instead of remembering to filter by hand in
 * every route.
 *
 * Two clients are exported:
 *   • `db`             — TENANT-SCOPED. Auto-injects `tenantId` from the current
 *                        request's AsyncLocalStorage context. Use this for all
 *                        tenant-bound work (Hostel Admin, Warden, etc.).
 *   • `prismaUnscoped` — RAW, no scoping. Use ONLY for the handful of
 *                        legitimately cross-tenant operations, each of which is
 *                        auditable by grepping for this name:
 *                          - login lookup by unique email (pre-auth)
 *                          - SUPER_ADMIN platform operations
 *                          - tests / seeds
 *
 * The scoped client is FAIL-CLOSED: if a scoped model is queried without a
 * tenant context (or with a null tenantId), it throws rather than returning
 * unscoped rows.
 */

// Models that carry a `tenantId` column and must be scoped. Every tenant-scoped
// table denormalizes `tenantId` so this one central layer isolates them all.
const TENANT_SCOPED_MODELS = new Set([
  'User',
  'Property',
  'Room',
  'Bed',
  'StudentProfile',
  'TenantSettings',
  'Invoice',
  'Payment',
  'Expense',
  'MessMenu',
  'MessAttendance',
  'MessDay',
  'MessSubscription',
  'MessInventoryItem',
  'MessStockEntry',
  'MessComplaint',
  'MessComplaintReply',
  'StudentRequest',
  'StudentRequestReply',
  'ReminderLog',
  'NotificationLog',
  'InvoiceLine',
  'ChargeType',
  'ChargeAssignment',
  'StudentCharge',
  'PaymentRequest',
  'HostelPaymentAccount',
  'VirtualAccount',
  'ReconciliationRun',
  'RoomAssetTemplate',
  'RoomAssetCheck',
  'MoveOut',
  'Settlement',
  'Stay',
  'GatePass',
  'GatePunch',
  'Visitor',
  'GuardianLink',
  'GatePass',
  'GatePunch',
  'Visitor',
  'GuardianLink',
  'MessMealOptOut',
  'RequestSla',
  'Vendor',
  'Enquiry',
  'Notice',
  'CustomRole',
  'BiometricDevice',
  'BiometricPunch',
  // tenantId is null on platform rows (CRM / unmatched replies); hostel
  // reads through `db` only ever see their own.
  'WhatsAppMessage',
  // Sprint 0 (TEPL foundation)
  'Attachment',
  'InboxItem',
  'ReportSchedule',
  // Sprint 1 (TEPL)
  'Department',
  'DepartmentApprover',
  'LeaveType',
  'LeaveAllocation',
  'Shift',
  'RosterEntry',
  // Sprint 2 (TEPL)
  'DisciplineIncident',
  'Feedback',
  'Parcel',
  'EmergencyContact',
  'LostFoundItem',
  // Sprint 3 (TEPL)
  'CleaningArea',
  'CleaningTask',
  'RoomAsset',
  'RoomAudit',
  'WorkOrder',
  'StoreItem',
  'StoreMovement',
  'LaundryOrder',
  'LaundryBatch',
  'StaffPunch',
  'StaffDuty',
  'EnergyMeter',
  'MeterReading',
  // Sprint 4 (TEPL)
  'NoticeAck',
  'WhatsAppBroadcast',
  'CurfewBreach',
  'Vehicle',
  'BusTrip',
  'EnergySetting',
  'EnergyAlert',
  // Sprint 5 (TEPL)
  'Event',
  'EventRegistration',
  'EmergencyAlert',
  'EmergencyAck',
  'EmergencyTeamMember',
  'MealWindow',
  'DietProfile',
  'DietMenu',
  'MealRating',
  // Sprint 6 (TEPL)
  'MedicalRecord',
  'OhcVisit',
  'MedicalAppointment',
  'MedicalAccessLog',
  'AccessibilityProfile',
  'AssistanceRequest',
  'IntegrationRun',
  // Sprint 7 (TEPL)
  'ComplianceItem',
  'ComplianceInspection',
  'ComplianceFinding',
  'ComplianceAudit',
]);

function requireTenantId(model: string): string {
  const ctx = getTenantContext();
  if (!ctx) {
    throw new Error(
      `Tenant scope violation: query on "${model}" ran without a tenant context. ` +
        `Use prismaUnscoped for intentional cross-tenant/pre-auth operations.`,
    );
  }
  if (!ctx.tenantId) {
    throw new Error(
      `Tenant scope violation: query on "${model}" ran with a null tenantId ` +
        `(role ${ctx.role}). SUPER_ADMIN cross-tenant work must use prismaUnscoped.`,
    );
  }
  return ctx.tenantId;
}

/** AND a tenantId predicate into an existing `where` without clobbering it. */
function withTenantWhere(where: unknown, tenantId: string): Record<string, unknown> {
  const existing = (where ?? {}) as Record<string, unknown>;
  if (existing.tenantId !== undefined) return existing; // caller was explicit; respect it
  return { ...existing, tenantId };
}

export const prismaUnscoped = new PrismaClient({
  log: process.env.NODE_ENV === 'development' ? ['warn', 'error'] : ['warn', 'error'],
});

/**
 * The reusable tenant-scoping extension. Exported so the isolation test can
 * apply the exact same logic to a throwaway test database and prove it holds.
 */
export const tenantScopeExtension = {
  name: 'tenant-scope',
  query: {
    $allModels: {
      async $allOperations({ model, operation, args, query }: {
        model: string;
        operation: string;
        args: unknown;
        query: (args: unknown) => Promise<unknown>;
      }) {
        if (!TENANT_SCOPED_MODELS.has(model)) {
          return query(args);
        }
        const tenantId = requireTenantId(model);
        const a = (args ?? {}) as Record<string, unknown>;

        switch (operation) {
          // Writes: stamp tenantId onto the created row(s).
          case 'create':
            a.data = { ...(a.data as object), tenantId };
            return query(a);
          case 'createMany': {
            const data = a.data as Record<string, unknown> | Record<string, unknown>[];
            a.data = Array.isArray(data)
              ? data.map((d) => ({ ...d, tenantId }))
              : { ...data, tenantId };
            return query(a);
          }
          case 'upsert':
            a.where = withTenantWhere(a.where, tenantId);
            a.create = { ...(a.create as object), tenantId };
            return query(a);

          // where-based ops: constrain to this tenant.
          case 'findFirst':
          case 'findFirstOrThrow':
          case 'findMany':
          case 'count':
          case 'aggregate':
          case 'groupBy':
          case 'update':
          case 'updateMany':
          case 'delete':
          case 'deleteMany':
            a.where = withTenantWhere(a.where, tenantId);
            return query(a);

          // findUnique can't take a non-unique field in `where`, so we run it
          // and verify ownership afterwards (fail-closed).
          case 'findUnique':
          case 'findUniqueOrThrow': {
            const result = (await query(a)) as { tenantId?: string } | null;
            if (result && result.tenantId !== tenantId) {
              if (operation === 'findUniqueOrThrow') {
                throw new Error('No record found (tenant scope)');
              }
              return null;
            }
            return result;
          }

          default:
            return query(a);
        }
      },
    },
  },
} as const;

export const db = prismaUnscoped.$extends(tenantScopeExtension);

export type ScopedDb = typeof db;
