/**
 * Tenant-isolation integration test — the sign-off gate for Sprint 1 task #2.
 *
 * Proves the central scoping layer prevents cross-tenant data access:
 *   "Can Tenant A ever read/modify Tenant B's data?"  →  it must not.
 *
 * Runs against a THROWAWAY schema (hc_test) so dev data is never touched.
 * Invoked via `npm run test:isolation` (see package.json), which sets
 * DATABASE_URL to the hc_test schema and pushes the schema first.
 */
import test from 'node:test';
import assert from 'node:assert/strict';
import { PrismaClient, Role } from '@prisma/client';
import { tenantScopeExtension } from '../lib/prisma';
import { runWithTenantContext } from '../lib/tenantContext';

const raw = new PrismaClient(); // unscoped — for seeding + assertions
const scoped = raw.$extends(tenantScopeExtension); // the real scoping logic

let tenantAId = '';
let tenantBId = '';
let userB1Id = '';

test('seed two tenants with users (unscoped)', async () => {
  // Clean slate within the throwaway schema.
  await raw.user.deleteMany({});
  await raw.tenant.deleteMany({});

  const a = await raw.tenant.create({ data: { name: 'Tenant A' } });
  const b = await raw.tenant.create({ data: { name: 'Tenant B' } });
  tenantAId = a.id;
  tenantBId = b.id;

  await raw.user.create({
    data: { tenantId: a.id, role: Role.HOSTEL_ADMIN, name: 'A Admin', email: 'a-admin@test.local', passwordHash: 'x' },
  });
  await raw.user.create({
    data: { tenantId: a.id, role: Role.WARDEN, name: 'A Warden', email: 'a-warden@test.local', passwordHash: 'x' },
  });
  const b1 = await raw.user.create({
    data: { tenantId: b.id, role: Role.HOSTEL_ADMIN, name: 'B Admin', email: 'b-admin@test.local', passwordHash: 'x' },
  });
  userB1Id = b1.id;
});

const ctxA = () => ({ userId: 'u', role: Role.HOSTEL_ADMIN, tenantId: tenantAId });

/**
 * Run `fn` inside a tenant context AND await it there. Prisma queries are lazy
 * (execution happens on await), so the await MUST occur within the ALS scope —
 * exactly as Express does when it runs a route handler inside authenticate().
 */
function runAs<T>(ctx: ReturnType<typeof ctxA> | { userId: string; role: Role; tenantId: string | null }, fn: () => Promise<T>): Promise<T> {
  return runWithTenantContext(ctx, async () => await fn());
}

test('findMany returns only the current tenant’s rows', async () => {
  const users = await runAs(ctxA(), () => scoped.user.findMany({}));
  assert.equal(users.length, 2, 'Tenant A should see exactly its own 2 users');
  assert.ok(users.every((u) => u.tenantId === tenantAId), 'no row may belong to another tenant');
  assert.ok(users.every((u) => u.tenantId !== tenantBId), 'Tenant B’s rows must never appear');
});

test('findUnique on another tenant’s row returns null (fail-closed)', async () => {
  const leaked = await runAs(ctxA(), () => scoped.user.findUnique({ where: { id: userB1Id } }));
  assert.equal(leaked, null, 'Tenant A must not read Tenant B’s user by id');
});

test('updateMany cannot touch another tenant’s rows', async () => {
  const res = await runAs(ctxA(), () => scoped.user.updateMany({ data: { name: 'HACKED' } }));
  assert.equal(res.count, 2, 'update should affect only Tenant A’s 2 users');
  const b1 = await raw.user.findUnique({ where: { id: userB1Id } });
  assert.equal(b1?.name, 'B Admin', 'Tenant B’s row must be untouched');
});

test('create auto-stamps the current tenantId', async () => {
  const created = await runAs(ctxA(), () =>
    scoped.user.create({
      data: { role: Role.MESS_ADMIN, name: 'A Mess', email: 'a-mess@test.local', passwordHash: 'x' },
    }),
  );
  assert.equal(created.tenantId, tenantAId, 'new row must belong to the acting tenant');
});

test('querying a scoped model with NO context throws (fail-closed)', async () => {
  await assert.rejects(() => scoped.user.findMany({}), /Tenant scope violation/);
});

test('querying with a null tenantId (e.g. SUPER_ADMIN) throws', async () => {
  await assert.rejects(
    () => runAs({ userId: 'super', role: Role.SUPER_ADMIN, tenantId: null }, () => scoped.user.findMany({})),
    /null tenantId/,
  );
});

test('Room (a Sprint 2 scoped model) is isolated across tenants', async () => {
  const propA = await raw.property.create({ data: { tenantId: tenantAId, name: 'Prop A' } });
  const propB = await raw.property.create({ data: { tenantId: tenantBId, name: 'Prop B' } });
  await raw.room.create({ data: { tenantId: tenantAId, propertyId: propA.id, number: 'A-101' } });
  const roomB = await raw.room.create({ data: { tenantId: tenantBId, propertyId: propB.id, number: 'B-101' } });

  const seenByA = await runAs(ctxA(), () => scoped.room.findMany({}));
  assert.equal(seenByA.length, 1, 'Tenant A sees only its own room');
  assert.equal(seenByA[0].number, 'A-101');

  const leaked = await runAs(ctxA(), () => scoped.room.findUnique({ where: { id: roomB.id } }));
  assert.equal(leaked, null, 'Tenant A must not read Tenant B’s room');

  const created = await runAs(ctxA(), () =>
    scoped.room.create({ data: { tenantId: tenantAId, propertyId: propA.id, number: 'A-102' } }),
  );
  assert.equal(created.tenantId, tenantAId, 'new room is stamped with the acting tenant');
});

test('MessDay (the mess calendar) is isolated across tenants', async () => {
  // Newly scoped models are the easy ones to forget. A menu leaking between
  // hostels would be the mildest symptom of that mistake.
  await raw.messDay.create({ data: { tenantId: tenantAId, date: new Date('2030-01-01T00:00:00.000Z'), lunch: 'A lunch' } });
  const dayB = await raw.messDay.create({
    data: { tenantId: tenantBId, date: new Date('2030-01-01T00:00:00.000Z'), lunch: 'B lunch' },
  });

  const seenByA = await runAs(ctxA(), () => scoped.messDay.findMany({}));
  assert.equal(seenByA.length, 1, 'Tenant A sees only its own calendar');
  assert.equal(seenByA[0].lunch, 'A lunch');

  const leaked = await runAs(ctxA(), () => scoped.messDay.findUnique({ where: { id: dayB.id } }));
  assert.equal(leaked, null, 'Tenant A must not read Tenant B’s mess day');
});

test('MessInventoryItem and MessComplaint are scoped too', async () => {
  await raw.messInventoryItem.create({ data: { tenantId: tenantBId, name: 'Rice', unit: 'kg' } });
  const itemsSeenByA = await runAs(ctxA(), () => scoped.messInventoryItem.findMany({}));
  assert.equal(itemsSeenByA.length, 0, 'Tenant A must not see Tenant B’s stock list');

  const created = await runAs(ctxA(), () => scoped.messInventoryItem.create({ data: { tenantId: tenantAId, name: 'Dal', unit: 'kg' } }));
  assert.equal(created.tenantId, tenantAId, 'new item is stamped with the acting tenant');
});

test('Invoice (Sprint 3 financial data) is isolated across tenants', async () => {
  // Seed a student + invoice for each tenant.
  const seed = async (tenantId: string, tag: string) => {
    const u = await raw.user.create({
      data: { tenantId, role: Role.STUDENT, name: `${tag} Student`, email: `${tag}-stud@test.local`, passwordHash: 'x' },
    });
    const p = await raw.studentProfile.create({ data: { tenantId, userId: u.id } });
    return raw.invoice.create({ data: { tenantId, studentProfileId: p.id, type: 'RENT', periodMonth: '2026-07', amount: 5000 } });
  };
  await seed(tenantAId, 'iso-a');
  const invB = await seed(tenantBId, 'iso-b');

  const seenByA = await runAs(ctxA(), () => scoped.invoice.findMany({}));
  assert.equal(seenByA.length, 1, 'Tenant A sees only its own invoice');
  assert.ok(seenByA.every((i) => i.tenantId === tenantAId), 'no invoice from another tenant');

  const leaked = await runAs(ctxA(), () => scoped.invoice.findUnique({ where: { id: invB.id } }));
  assert.equal(leaked, null, 'Tenant A must not read Tenant B’s invoice');
});

test('Enquiry and Vendor (Sprint 6) are isolated across tenants', async () => {
  // The public form writes enquiries without a session, so the scoped read
  // side is the only wall between two hostels' prospect lists.
  const propA = (await raw.property.findFirst({ where: { tenantId: tenantAId } })) ?? (await raw.property.create({ data: { tenantId: tenantAId, name: 'Prop A' } }));
  const propB = (await raw.property.findFirst({ where: { tenantId: tenantBId } })) ?? (await raw.property.create({ data: { tenantId: tenantBId, name: 'Prop B' } }));
  await raw.enquiry.create({ data: { tenantId: tenantAId, propertyId: propA.id, name: 'A prospect', phone: '1' } });
  const enqB = await raw.enquiry.create({ data: { tenantId: tenantBId, propertyId: propB.id, name: 'B prospect', phone: '2' } });
  await raw.vendor.create({ data: { tenantId: tenantBId, name: 'B plumber' } });

  const seenByA = await runAs(ctxA(), () => scoped.enquiry.findMany({}));
  assert.equal(seenByA.length, 1, 'Tenant A sees only its own enquiries');
  assert.equal(seenByA[0].name, 'A prospect');
  const leaked = await runAs(ctxA(), () => scoped.enquiry.findUnique({ where: { id: enqB.id } }));
  assert.equal(leaked, null, 'Tenant A must not read Tenant B’s enquiry');
  const vendors = await runAs(ctxA(), () => scoped.vendor.findMany({}));
  assert.equal(vendors.length, 0, 'Tenant A sees none of Tenant B’s vendors');
});

test('device tokens (push) stay with their own user', async () => {
  // Tokens carry no tenantId: the wall is the user id from the session.
  const { registerDevice, unregisterDevice, tokensByUser } = await import('../modules/devices/devices.service');
  const a = await raw.user.findFirstOrThrow({ where: { tenantId: tenantAId, role: Role.HOSTEL_ADMIN } });
  await registerDevice(a.id, 'token-a-0123456789', 'ANDROID');
  await registerDevice(userB1Id, 'token-b-0123456789', 'IOS');

  const forA = await tokensByUser([a.id]);
  assert.deepEqual(forA.get(a.id), ['token-a-0123456789'], 'A gets only A’s phone');
  assert.equal(forA.has(userB1Id), false, 'B’s phone is not in A’s push');

  assert.equal(await unregisterDevice(userB1Id, 'token-a-0123456789'), 0, 'B cannot sign A’s phone out of push');
  assert.equal((await tokensByUser([a.id])).get(a.id)?.length, 1, 'A’s phone is still registered');

  // One install is one token: B signing in on A’s old phone takes it over.
  await registerDevice(userB1Id, 'token-a-0123456789', 'ANDROID');
  assert.equal((await tokensByUser([a.id])).has(a.id), false, 'the phone no longer pushes to A');
  assert.equal((await tokensByUser([userB1Id])).get(userB1Id)?.length, 2);
  await raw.deviceToken.deleteMany({});
});

test('Attachment, InboxItem and ReportSchedule (Sprint 0, TEPL) are isolated across tenants', async () => {
  const a = await raw.user.findFirstOrThrow({ where: { tenantId: tenantAId, role: Role.HOSTEL_ADMIN } });
  await raw.attachment.create({ data: { tenantId: tenantAId, ownerType: 'REQUEST', ownerId: a.id, key: 'k-a', name: 'a.png', contentType: 'image/png', size: 1, uploadedById: a.id } });
  const fileB = await raw.attachment.create({ data: { tenantId: tenantBId, ownerType: 'REQUEST', ownerId: userB1Id, key: 'k-b', name: 'b.png', contentType: 'image/png', size: 1, uploadedById: userB1Id } });
  await raw.inboxItem.create({ data: { tenantId: tenantBId, userId: userB1Id, kind: 'NOTICE', refId: 'n1', title: 'B only', body: 'x' } });
  await raw.reportSchedule.create({ data: { tenantId: tenantBId, reportKey: 'occupancy', frequency: 'DAILY', recipients: ['b@test.local'], createdById: userB1Id } });

  const files = await runAs(ctxA(), () => scoped.attachment.findMany({}));
  assert.equal(files.length, 1, 'Tenant A sees only its own attachment');
  assert.equal(await runAs(ctxA(), () => scoped.attachment.findUnique({ where: { id: fileB.id } })), null, 'Tenant A must not read Tenant B’s file');
  assert.equal((await runAs(ctxA(), () => scoped.inboxItem.findMany({}))).length, 0, 'Tenant A sees none of Tenant B’s inbox');
  assert.equal((await runAs(ctxA(), () => scoped.reportSchedule.findMany({}))).length, 0, 'Tenant A sees none of Tenant B’s schedules');
  const moved = await runAs(ctxA(), () => scoped.reportSchedule.updateMany({ data: { hour: 1 } }));
  assert.equal(moved.count, 0, 'Tenant A cannot change Tenant B’s schedules');
});

test('departments, leave and roster (Sprint 1, TEPL) are isolated across tenants', async () => {
  const deptB = await raw.department.create({ data: { tenantId: tenantBId, name: 'B Assembly' } });
  await raw.departmentApprover.create({ data: { tenantId: tenantBId, departmentId: deptB.id, userId: userB1Id } });
  const typeB = await raw.leaveType.create({ data: { tenantId: tenantBId, code: 'CL', name: 'Casual leave', yearlyDays: 12 } });
  const shiftB = await raw.shift.create({ data: { tenantId: tenantBId, code: 'A', name: 'First', startTime: '06:00', endTime: '14:00' } });
  const studB = await raw.studentProfile.findFirst({ where: { tenantId: tenantBId } });
  if (studB) {
    await raw.leaveAllocation.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, leaveTypeId: typeB.id, year: 2026, allotted: 12 } });
    await raw.rosterEntry.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, date: new Date('2026-11-10T00:00:00Z'), shiftId: shiftB.id } });
  }
  for (const model of ['department', 'departmentApprover', 'leaveType', 'leaveAllocation', 'shift', 'rosterEntry'] as const) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const rows = (await runAs(ctxA(), () => (scoped as any)[model].findMany({}))) as unknown[];
    assert.equal(rows.length, 0, `Tenant A sees none of Tenant B’s ${model} rows`);
  }
  assert.equal(await runAs(ctxA(), () => scoped.department.findUnique({ where: { id: deptB.id } })), null, 'Tenant A must not read Tenant B’s department');
  const renamed = await runAs(ctxA(), () => scoped.shift.updateMany({ data: { name: 'x' } }));
  assert.equal(renamed.count, 0, 'Tenant A cannot change Tenant B’s shifts');
});

test('discipline, feedback, parcels, contacts and lost and found (Sprint 2, TEPL) are isolated across tenants', async () => {
  const studB = await raw.studentProfile.findFirst({ where: { tenantId: tenantBId } });
  if (studB) {
    await raw.disciplineIncident.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, occurredAt: new Date(), category: 'NOISE', severity: 'MINOR', description: 'B only', reportedById: userB1Id } });
    await raw.parcel.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, receivedById: userB1Id } });
  }
  await raw.feedback.create({ data: { tenantId: tenantBId, submitterKey: 'b-key', period: '2026-11', ratings: { FOOD: 5 } } });
  await raw.emergencyContact.create({ data: { tenantId: tenantBId, name: 'B warden', role: 'WARDEN', phone: '1' } });
  const itemB = await raw.lostFoundItem.create({ data: { tenantId: tenantBId, kind: 'FOUND', title: 'B wallet', happenedAt: new Date(), reportedById: userB1Id } });
  for (const model of ['disciplineIncident', 'feedback', 'parcel', 'emergencyContact', 'lostFoundItem'] as const) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const rows = (await runAs(ctxA(), () => (scoped as any)[model].findMany({}))) as unknown[];
    assert.equal(rows.length, 0, `Tenant A sees none of Tenant B’s ${model} rows`);
  }
  assert.equal(await runAs(ctxA(), () => scoped.lostFoundItem.findUnique({ where: { id: itemB.id } })), null, 'Tenant A must not read Tenant B’s found item');
  const claimed = await runAs(ctxA(), () => scoped.lostFoundItem.updateMany({ data: { status: 'CLAIMED' } }));
  assert.equal(claimed.count, 0, 'Tenant A cannot claim Tenant B’s items');
});

test('cleaning, room inventory, laundry, staff attendance and energy (Sprint 3, TEPL) are isolated across tenants', async () => {
  const propB = await raw.property.findFirstOrThrow({ where: { tenantId: tenantBId } });
  const studB = await raw.studentProfile.findFirst({ where: { tenantId: tenantBId } });
  const areaB = await raw.cleaningArea.create({ data: { tenantId: tenantBId, propertyId: propB.id, name: 'B corridor', kind: 'CORRIDOR', frequency: 'DAILY' } });
  await raw.cleaningTask.create({ data: { tenantId: tenantBId, propertyId: propB.id, areaId: areaB.id, dueDate: new Date('2026-11-03T00:00:00.000Z'), slot: 'DAY' } });
  const roomB = await raw.room.findFirst({ where: { tenantId: tenantBId } });
  if (roomB) {
    await raw.roomAsset.create({ data: { tenantId: tenantBId, propertyId: propB.id, roomId: roomB.id, name: 'B fan' } });
    await raw.roomAudit.create({ data: { tenantId: tenantBId, propertyId: propB.id, roomId: roomB.id, auditedById: userB1Id, items: [] } });
  }
  const woB = await raw.workOrder.create({ data: { tenantId: tenantBId, title: 'B repair', createdById: userB1Id } });
  const itemB = await raw.storeItem.create({ data: { tenantId: tenantBId, name: 'B sheets' } });
  await raw.storeMovement.create({ data: { tenantId: tenantBId, itemId: itemB.id, direction: 'IN', quantity: 1, recordedById: userB1Id } });
  if (studB) await raw.laundryOrder.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, items: 3 } });
  await raw.laundryBatch.create({ data: { tenantId: tenantBId, sentById: userB1Id } });
  await raw.staffPunch.create({ data: { tenantId: tenantBId, userId: userB1Id, direction: 'IN', at: new Date() } });
  const shiftB = await raw.shift.findFirst({ where: { tenantId: tenantBId } });
  if (shiftB) await raw.staffDuty.create({ data: { tenantId: tenantBId, userId: userB1Id, date: new Date('2026-11-03T00:00:00.000Z'), shiftId: shiftB.id } });
  const meterB = await raw.energyMeter.create({ data: { tenantId: tenantBId, propertyId: propB.id, code: 'B-1', name: 'B meter' } });
  await raw.meterReading.create({ data: { tenantId: tenantBId, meterId: meterB.id, readAt: new Date(), kwh: 1 } });
  for (const model of ['cleaningArea', 'cleaningTask', 'roomAsset', 'roomAudit', 'workOrder', 'storeItem', 'storeMovement', 'laundryOrder', 'laundryBatch', 'staffPunch', 'staffDuty', 'energyMeter', 'meterReading'] as const) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const rows = (await runAs(ctxA(), () => (scoped as any)[model].findMany({}))) as unknown[];
    assert.equal(rows.length, 0, `Tenant A sees none of Tenant B’s ${model} rows`);
  }
  assert.equal(await runAs(ctxA(), () => scoped.workOrder.findUnique({ where: { id: woB.id } })), null, 'Tenant A must not read Tenant B’s work order');
  const moved = await runAs(ctxA(), () => scoped.storeItem.updateMany({ data: { quantity: 999 } }));
  assert.equal(moved.count, 0, 'Tenant A cannot change Tenant B’s stock');
  const ticked = await runAs(ctxA(), () => scoped.cleaningTask.updateMany({ data: { status: 'DONE' } }));
  assert.equal(ticked.count, 0, 'Tenant A cannot tick Tenant B’s cleaning');
});

test('notice receipts, broadcasts, curfew, buses and energy KPIs (Sprint 4, TEPL) are isolated across tenants', async () => {
  const propB = await raw.property.findFirstOrThrow({ where: { tenantId: tenantBId } });
  const studB = await raw.studentProfile.findFirst({ where: { tenantId: tenantBId } });
  const noticeB = await raw.notice.create({ data: { tenantId: tenantBId, title: 'B only', body: 'B', postedById: userB1Id, postedByName: 'B', requireAck: true } });
  await raw.noticeAck.create({ data: { tenantId: tenantBId, noticeId: noticeB.id, userId: userB1Id } });
  await raw.whatsAppBroadcast.create({ data: { tenantId: tenantBId, title: 'B', body: 'B', audience: {}, createdById: userB1Id } });
  if (studB) await raw.curfewBreach.create({ data: { tenantId: tenantBId, propertyId: propB.id, studentProfileId: studB.id, date: new Date('2026-11-03T00:00:00.000Z') } });
  const busB = await raw.vehicle.create({ data: { tenantId: tenantBId, number: 'B-BUS-1' } });
  await raw.busTrip.create({ data: { tenantId: tenantBId, vehicleId: busB.id, departedAt: new Date() } });
  await raw.energySetting.create({ data: { tenantId: tenantBId, bmsPullUrl: 'https://bms.example/b' } });
  const meterB = await raw.energyMeter.findFirst({ where: { tenantId: tenantBId } });
  if (meterB) await raw.energyAlert.create({ data: { tenantId: tenantBId, propertyId: propB.id, meterId: meterB.id, date: new Date('2026-11-02T00:00:00.000Z'), kwh: 9, baseline: 2 } });
  for (const model of ['noticeAck', 'whatsAppBroadcast', 'curfewBreach', 'vehicle', 'busTrip', 'energySetting', 'energyAlert'] as const) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const rows = (await runAs(ctxA(), () => (scoped as any)[model].findMany({}))) as unknown[];
    assert.equal(rows.length, 0, `Tenant A sees none of Tenant B’s ${model} rows`);
  }
  assert.equal(await runAs(ctxA(), () => scoped.vehicle.findUnique({ where: { id: busB.id } })), null, 'Tenant A must not read Tenant B’s vehicle');
  const closed = await runAs(ctxA(), () => scoped.busTrip.updateMany({ data: { arrivedAt: new Date() } }));
  assert.equal(closed.count, 0, 'Tenant A cannot close Tenant B’s trips');
  const ack = await runAs(ctxA(), () => scoped.energyAlert.updateMany({ data: { status: 'ACKNOWLEDGED' } }));
  assert.equal(ack.count, 0, 'Tenant A cannot acknowledge Tenant B’s alerts');
});

test('events, emergencies, the canteen (Sprint 5, TEPL) are isolated across tenants', async () => {
  const studB = await raw.studentProfile.findFirst({ where: { tenantId: tenantBId } });
  const evB = await raw.event.create({ data: { tenantId: tenantBId, title: 'B match', startsAt: new Date(), endsAt: new Date(Date.now() + 3_600_000), createdById: userB1Id } });
  const alertB = await raw.emergencyAlert.create({ data: { tenantId: tenantBId, title: 'B fire', message: 'B', raisedById: userB1Id } });
  if (studB) {
    await raw.eventRegistration.create({ data: { tenantId: tenantBId, eventId: evB.id, studentProfileId: studB.id } });
    await raw.emergencyAck.create({ data: { tenantId: tenantBId, alertId: alertB.id, studentProfileId: studB.id, status: 'SAFE' } });
    await raw.dietProfile.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, preference: 'JAIN' } });
    await raw.mealRating.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, date: new Date('2026-11-03T00:00:00.000Z'), meal: 'LUNCH', rating: 3 } });
  }
  await raw.emergencyTeamMember.create({ data: { tenantId: tenantBId, name: 'B warden', phone: '1', role: 'FIRE_WARDEN' } });
  await raw.mealWindow.create({ data: { tenantId: tenantBId, meal: 'LUNCH', startTime: '12:00', endTime: '14:00' } });
  await raw.dietMenu.create({ data: { tenantId: tenantBId, dayOfWeek: 1, meal: 'LUNCH', diet: 'JAIN', items: 'B dal' } });
  for (const model of ['event', 'eventRegistration', 'emergencyAlert', 'emergencyAck', 'emergencyTeamMember', 'mealWindow', 'dietProfile', 'dietMenu', 'mealRating'] as const) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const rows = (await runAs(ctxA(), () => (scoped as any)[model].findMany({}))) as unknown[];
    assert.equal(rows.length, 0, `Tenant A sees none of Tenant B’s ${model} rows`);
  }
  assert.equal(await runAs(ctxA(), () => scoped.emergencyAlert.findUnique({ where: { id: alertB.id } })), null, 'Tenant A must not read Tenant B’s alert');
  const closed = await runAs(ctxA(), () => scoped.emergencyAlert.updateMany({ data: { closedAt: new Date() } }));
  assert.equal(closed.count, 0, 'Tenant A cannot close Tenant B’s alerts');
  const cancelled = await runAs(ctxA(), () => scoped.event.updateMany({ data: { status: 'CANCELLED' } }));
  assert.equal(cancelled.count, 0, 'Tenant A cannot cancel Tenant B’s events');
});

test('medical records, special needs, HR feed runs (Sprint 6, TEPL) are isolated, and medical records are sealed at rest', async () => {
  const { sealJson, openJson, medicalContext } = await import('../lib/medicalCrypto');
  const studB = await raw.studentProfile.findFirst({ where: { tenantId: tenantBId } });
  if (studB) {
    const sealed = sealJson({ allergies: 'Penicillin', conditions: ['Asthma'] }, medicalContext(tenantBId, studB.id));
    assert.ok(!sealed.includes('Penicillin') && !sealed.includes('Asthma'), 'a sealed record shows none of its words');
    assert.deepEqual(openJson<{ allergies: string }>(sealed, medicalContext(tenantBId, studB.id)).allergies, 'Penicillin');
    // Sprint 7: bound to whose record it is — copied to another employee or tenant, it will not open.
    assert.throws(() => openJson(sealed, medicalContext(tenantBId, 'someone-else')));
    assert.throws(() => openJson(sealed, medicalContext(tenantAId, studB.id)));
    assert.throws(() => openJson(sealed));
    await raw.medicalRecord.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, sealed, consentAt: new Date(), updatedById: userB1Id } });
    await raw.ohcVisit.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, at: new Date(), sealed: sealJson({ complaint: 'B' }), createdById: userB1Id } });
    await raw.medicalAppointment.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, at: new Date(), purpose: 'Follow-up', createdById: userB1Id } });
    await raw.medicalAccessLog.create({ data: { tenantId: tenantBId, userId: userB1Id, studentProfileId: studB.id, action: 'VIEW' } });
    await raw.accessibilityProfile.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, categories: ['MOBILITY'] } });
    await raw.assistanceRequest.create({ data: { tenantId: tenantBId, studentProfileId: studB.id, kind: 'ESCORT' } });
  }
  await raw.integrationRun.create({ data: { tenantId: tenantBId, kind: 'ROSTER', source: 'FEED', received: 1, accepted: 1, failed: 0, errors: [] } });
  for (const model of ['medicalRecord', 'ohcVisit', 'medicalAppointment', 'medicalAccessLog', 'accessibilityProfile', 'assistanceRequest', 'integrationRun'] as const) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const rows = (await runAs(ctxA(), () => (scoped as any)[model].findMany({}))) as unknown[];
    assert.equal(rows.length, 0, `Tenant A sees none of Tenant B’s ${model} rows`);
  }
  const touched = await runAs(ctxA(), () => scoped.medicalRecord.updateMany({ data: { consentWithdrawnAt: new Date() } }));
  assert.equal(touched.count, 0, 'Tenant A cannot touch Tenant B’s medical records');
});

test('statutory compliance (Sprint 7, TEPL) is isolated', async () => {
  const item = await raw.complianceItem.create({ data: { tenantId: tenantBId, kind: 'LICENCE', name: 'B licence', expiresOn: new Date('2027-01-01T00:00:00.000Z'), createdById: userB1Id } });
  const ins = await raw.complianceInspection.create({ data: { tenantId: tenantBId, itemId: item.id, kind: 'STATUTORY', inspectedOn: new Date('2026-11-01T00:00:00.000Z'), inspector: 'B inspector', result: 'PASSED', createdById: userB1Id } });
  await raw.complianceFinding.create({ data: { tenantId: tenantBId, inspectionId: ins.id, description: 'B finding', severity: 'LOW', ownerId: userB1Id } });
  await raw.complianceAudit.create({ data: { tenantId: tenantBId, entityType: 'ITEM', entityId: item.id, action: 'CREATED', actorId: userB1Id } });
  for (const model of ['complianceItem', 'complianceInspection', 'complianceFinding', 'complianceAudit'] as const) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const rows = (await runAs(ctxA(), () => (scoped as any)[model].findMany({}))) as unknown[];
    assert.equal(rows.length, 0, `Tenant A sees none of Tenant B’s ${model} rows`);
  }
  const touched = await runAs(ctxA(), () => scoped.complianceItem.updateMany({ data: { name: 'taken over' } }));
  assert.equal(touched.count, 0, 'Tenant A cannot touch Tenant B’s compliance items');
  const svc = await import('../modules/compliance/compliance.service');
  await assert.rejects(runAs(ctxA(), () => svc.getItem(item.id)), 'Tenant A cannot open Tenant B’s item by id');
  await assert.rejects(runAs(ctxA(), () => svc.createInspection({ itemId: item.id, kind: 'INTERNAL', inspectedOn: new Date('2026-11-01T00:00:00.000Z'), inspector: 'A', result: 'PASSED' }, 'u')), 'Tenant A cannot hang an inspection on Tenant B’s item');
});

test('notice audience counts (Sprint L1, raw SQL) stay inside the tenant and follow the audience', async () => {
  const { audienceCountsForNotices } = await import('../modules/communication/audience');
  const block1 = await raw.property.create({ data: { tenantId: tenantAId, name: 'L1 block 1' } });
  const block2 = await raw.property.create({ data: { tenantId: tenantAId, name: 'L1 block 2' } });
  const room = await raw.room.create({ data: { tenantId: tenantAId, propertyId: block1.id, number: 'L1-201', floor: 2 } });
  const resident = async (tag: string, propertyId: string, opts: { floor2?: boolean; vacated?: boolean } = {}) => {
    const u = await raw.user.create({ data: { tenantId: tenantAId, role: Role.STUDENT, name: tag, email: `${tag}@test.local`, passwordHash: 'x' } });
    const bed = opts.floor2 ? await raw.bed.create({ data: { tenantId: tenantAId, roomId: room.id, label: tag } }) : null;
    await raw.studentProfile.create({ data: { tenantId: tenantAId, userId: u.id, propertyId, bedId: bed?.id, residencyStatus: opts.vacated ? 'VACATED' : 'ACTIVE' } });
  };
  await resident('l1-a', block1.id, { floor2: true });
  await resident('l1-b', block1.id);
  await resident('l1-c', block2.id);
  await resident('l1-gone', block1.id, { vacated: true });
  // Department, usual shift and today's roster narrow too.
  const dept = await raw.department.create({ data: { tenantId: tenantAId, name: 'L1 Assembly' } });
  const shiftA = await raw.shift.create({ data: { tenantId: tenantAId, code: 'L1A', name: 'L1 A' } });
  const shiftB = await raw.shift.create({ data: { tenantId: tenantAId, code: 'L1B', name: 'L1 B' } });
  const worker = await raw.user.create({ data: { tenantId: tenantAId, role: Role.STUDENT, name: 'l1-w', email: 'l1-w@test.local', passwordHash: 'x' } });
  await raw.studentProfile.create({ data: { tenantId: tenantAId, userId: worker.id, propertyId: block2.id, departmentId: dept.id, defaultShiftId: shiftA.id } });
  const today = new Date(`${new Date(Date.now() + 330 * 60_000).toISOString().slice(0, 10)}T00:00:00.000Z`);
  const rostered = await raw.user.create({ data: { tenantId: tenantAId, role: Role.STUDENT, name: 'l1-r', email: 'l1-r@test.local', passwordHash: 'x' } });
  const rosteredProfile = await raw.studentProfile.create({ data: { tenantId: tenantAId, userId: rostered.id, propertyId: block2.id } });
  await raw.rosterEntry.create({ data: { tenantId: tenantAId, studentProfileId: rosteredProfile.id, date: today, shiftId: shiftB.id } });
  const notice = (tenantId: string, data: { propertyId?: string; floors?: number[]; departmentIds?: string[]; shiftIds?: string[] } = {}) =>
    raw.notice.create({ data: { tenantId, title: 'L1', body: 'x', postedById: 'u', postedByName: 'u', requireAck: true, ...data } });
  const everyone = await notice(tenantAId);
  const blockOne = await notice(tenantAId, { propertyId: block1.id });
  const floorTwo = await notice(tenantAId, { propertyId: block1.id, floors: [2] });
  const nobody = await notice(tenantAId, { floors: [9] });
  const byDept = await notice(tenantAId, { departmentIds: [dept.id] });
  const byShift = await notice(tenantAId, { shiftIds: [shiftA.id, shiftB.id] });
  const other = await notice(tenantBId);
  await raw.studentProfile.create({ data: { tenantId: tenantBId, userId: (await raw.user.create({ data: { tenantId: tenantBId, role: Role.STUDENT, name: 'l1-b-res', email: 'l1-b-res@test.local', passwordHash: 'x' } })).id } });

  const counts = await audienceCountsForNotices(tenantAId, [everyone, blockOne, floorTwo, nobody, byDept, byShift]);
  const all = await raw.studentProfile.count({ where: { tenantId: tenantAId, residencyStatus: { not: 'VACATED' } } });
  assert.equal(counts.get(everyone.id), all, 'an untargeted notice is for everyone in tenant A not moved out — none of B’s');
  assert.equal(counts.get(blockOne.id), 2, 'a block notice counts that block only');
  assert.equal(counts.get(floorTwo.id), 1, 'a floor narrows the block further');
  assert.equal(counts.get(nobody.id), 0, 'a notice nobody matches counts 0');
  assert.equal(counts.get(byDept.id), 1, 'a department notice counts its department');
  assert.equal(counts.get(byShift.id), 2, 'a shift notice counts usual shifts and today’s roster');
  // The same rule as the per-notice count it replaced.
  const { audienceWhere } = await import('../modules/communication/audience');
  for (const n of [everyone, blockOne, floorTwo, nobody, byDept, byShift]) {
    assert.equal(counts.get(n.id), await raw.studentProfile.count({ where: audienceWhere(tenantAId, n) }), `grouped count matches audienceWhere for ${n.id}`);
  }
  const forB = await audienceCountsForNotices(tenantBId, [other]);
  assert.equal(forB.get(other.id), await raw.studentProfile.count({ where: { tenantId: tenantBId } }), 'tenant B counts only its own residents');
});

test('invoice search keeps the selected block (a search once listed every block)', async () => {
  const { listInvoices, invoiceSummary } = await import('../modules/billing/billing.service');
  const blockA = await raw.property.create({ data: { tenantId: tenantAId, name: 'Search block A' } });
  const blockB = await raw.property.create({ data: { tenantId: tenantAId, name: 'Search block B' } });
  const seed = async (tag: string, propertyId: string) => {
    const u = await raw.user.create({ data: { tenantId: tenantAId, role: Role.STUDENT, name: `Asha ${tag}`, email: `search-${tag}@test.local`, passwordHash: 'x' } });
    const p = await raw.studentProfile.create({ data: { tenantId: tenantAId, userId: u.id, propertyId } });
    return raw.invoice.create({ data: { tenantId: tenantAId, studentProfileId: p.id, type: 'RENT', periodMonth: '2026-09', amount: 4000 } });
  };
  const inA = await seed('in-a', blockA.id);
  await seed('in-b', blockB.id);

  const filters = { period: '2026-09', propertyId: blockA.id, q: 'asha' };
  const rows = (await runAs(ctxA(), () => listInvoices(filters))) as { id: string }[];
  assert.deepEqual(rows.map((r) => r.id), [inA.id], 'a search inside block A lists block A only');

  const page = (await runAs(ctxA(), () => listInvoices(filters, { page: 1, limit: 20, skip: 0 }))) as { total: number };
  assert.equal(page.total, 1, 'the paged list counts block A only');

  const summary = await runAs(ctxA(), () => invoiceSummary(filters));
  assert.equal((summary as { billed: number }).billed, 4000, 'the summary adds up block A only');

  // Without a block, the search still finds both.
  const all = (await runAs(ctxA(), () => listInvoices({ period: '2026-09', q: 'asha' }))) as unknown[];
  assert.equal(all.length, 2);
});

test('Sprint L2 pages, floors, summaries and store totals stay inside the tenant', async () => {
  const gate = await import('../modules/gate/gate.service');
  const visitors = await import('../modules/gate/visitors.service');
  const rooms = await import('../modules/rooms/rooms.service');
  const stays = await import('../modules/stays/stays.service');
  const laundry = await import('../modules/laundry/laundry.service');
  const inv = await import('../modules/mess/inventory.service');
  const page = (p: number, limit: number) => ({ page: p, limit, skip: (p - 1) * limit });

  // Tenant A: one block, rooms on floors 1 and 2 and one with no floor; Tenant B: a block of its own.
  const seedBlock = async (tenantId: string, tag: string) => {
    const property = await raw.property.create({ data: { tenantId, name: `L2 ${tag}`, pricingMode: 'BED' } });
    const made: { id: string; floor: number | null }[] = [];
    for (const [number, floor] of [[`${tag}-101`, 1], [`${tag}-102`, 1], [`${tag}-201`, 2], [`${tag}-X`, null]] as const) {
      const room = await raw.room.create({ data: { tenantId, propertyId: property.id, number, floor } });
      await raw.bed.create({ data: { tenantId, roomId: room.id, label: 'A', status: 'VACANT', monthlyRent: 5000 } });
      await raw.bed.create({ data: { tenantId, roomId: room.id, label: 'B', status: 'OCCUPIED', monthlyRent: 5000 } });
      made.push({ id: room.id, floor });
    }
    const u = await raw.user.create({ data: { tenantId, role: Role.STUDENT, name: `L2 Ravi ${tag}`, email: `l2-${tag}@test.local`, passwordHash: 'x' } });
    const profile = await raw.studentProfile.create({ data: { tenantId, userId: u.id, propertyId: property.id } });
    return { property, rooms: made, profile };
  };
  const a = await seedBlock(tenantAId, 'a');
  const b = await seedBlock(tenantBId, 'b');

  // Floors and the floor filter.
  const floors = await runAs(ctxA(), () => rooms.roomFloors(a.property.id));
  assert.deepEqual(floors.floors.map((f) => [f.floor, f.rooms, f.beds, f.occupied, f.vacant]), [[1, 2, 4, 2, 2], [2, 1, 2, 1, 1], [null, 1, 2, 1, 1]], 'floors in order, unfloored last');
  assert.equal(floors.numbers.length, 4);
  assert.ok(floors.numbers.every((n) => n.startsWith('a-')), 'only tenant A’s room numbers');
  assert.deepEqual(floors.unflooredRoomIds, [a.rooms[3].id]);
  const allFloors = await runAs(ctxA(), () => rooms.roomFloors());
  assert.ok(allFloors.numbers.every((n) => !n.startsWith('b-')), 'no block of tenant B, even with no block chosen');
  const floor1 = (await runAs(ctxA(), () => rooms.listRooms(a.property.id, undefined, { floor: 1 }))) as { number: string }[];
  assert.deepEqual(floor1.map((r) => r.number), ['a-101', 'a-102']);
  const noFloor = (await runAs(ctxA(), () => rooms.listRooms(undefined, undefined, { floor: null }))) as { number: string }[];
  assert.ok(noFloor.some((r) => r.number === 'a-X') && !noFloor.some((r) => r.number.startsWith('b-')), 'floor null finds A’s unfloored room, never B’s');
  const roomPage = (await runAs(ctxA(), () => rooms.listRooms(a.property.id, undefined, { pagination: page(2, 3) }))) as { items: { number: string }[]; total: number; hasMore: boolean };
  assert.equal(roomPage.total, 4);
  assert.deepEqual(roomPage.items.map((r) => r.number), ['a-X'], 'page 2 of 3 holds the last room');
  assert.equal(roomPage.hasMore, false);

  // The dashboards' summary: vacant beds on floored rooms, 3 × 5000.
  const summary = await runAs(ctxA(), () => rooms.roomSummary(a.property.id));
  assert.equal(summary.vacantRent, 15000, 'unfloored rooms and tenant B’s beds are left out');
  assert.equal(summary.basis, 'MONTH');

  // Gate passes: newest first, a status filter that follows the clock, a day range, B's never.
  const now = Date.now();
  const pass = (tenantId: string, studentProfileId: string, hoursAgo: number, status: 'ACTIVE' | 'RETURNED', lengthH = 4) =>
    raw.gatePass.create({ data: { tenantId, studentProfileId, validFrom: new Date(now - hoursAgo * 3_600_000), validTo: new Date(now - hoursAgo * 3_600_000 + lengthH * 3_600_000), approvedById: 'u', tokenHash: `l2-${tenantId}-${hoursAgo}-${status}`, status } });
  await pass(tenantAId, a.profile.id, 1, 'ACTIVE'); // still valid
  await pass(tenantAId, a.profile.id, 50, 'ACTIVE'); // ran out: shows as EXPIRED
  await pass(tenantAId, a.profile.id, 30, 'RETURNED');
  await pass(tenantBId, b.profile.id, 2, 'ACTIVE');
  const passes = await runAs(ctxA(), () => gate.pagePasses(a.property.id, {}, page(1, 2)));
  assert.equal(passes.total, 3, 'tenant A’s three passes only');
  assert.equal(passes.items.length, 2);
  assert.ok(passes.hasMore);
  assert.ok(new Date(passes.items[0].validFrom) > new Date(passes.items[1].validFrom), 'newest first');
  const active = await runAs(ctxA(), () => gate.pagePasses(a.property.id, { status: 'ACTIVE' }, page(1, 20)));
  assert.equal(active.total, 1, 'ACTIVE leaves out a pass whose time ran out');
  const expired = await runAs(ctxA(), () => gate.pagePasses(a.property.id, { status: 'EXPIRED' }, page(1, 20)));
  assert.deepEqual(expired.items.map((p) => p.status), ['EXPIRED']);
  const day = new Date(now + 330 * 60_000).toISOString().slice(0, 10);
  const todays = await runAs(ctxA(), () => gate.pagePasses(a.property.id, { from: day, to: day }, page(1, 20)));
  assert.ok(todays.items.every((p) => new Date(p.validTo).getTime() >= Date.parse(`${day}T00:00:00+05:30`)), 'the day range keeps passes valid that day');
  const named = await runAs(ctxA(), () => gate.pagePasses(undefined, { q: 'ravi b' }, page(1, 20)));
  assert.equal(named.total, 0, 'a name search cannot reach tenant B’s resident');

  // Visitors, paged within the day.
  const visitDay = new Date().toISOString().slice(0, 10);
  for (let i = 0; i < 5; i++) await raw.visitor.create({ data: { tenantId: tenantAId, propertyId: a.property.id, name: `L2 guest ${i}`, status: 'OUT', inAt: new Date(`${visitDay}T0${i}:30:00Z`) } });
  await raw.visitor.create({ data: { tenantId: tenantBId, propertyId: b.property.id, name: 'L2 B guest', status: 'OUT', inAt: new Date(`${visitDay}T01:00:00Z`) } });
  const v1 = await runAs(ctxA(), () => visitors.pageVisitors(a.property.id, visitDay, undefined, page(1, 3)));
  const v2 = await runAs(ctxA(), () => visitors.pageVisitors(a.property.id, visitDay, undefined, page(2, 3)));
  assert.equal(v1.total, 5, 'tenant A’s visitors only');
  assert.equal(new Set([...v1.items, ...v2.items].map((v) => v.id)).size, 5, 'two pages hold all five, none twice');
  assert.equal(v2.hasMore, false);

  // Open stays for the rooms on screen.
  await raw.stay.create({ data: { tenantId: tenantAId, studentProfileId: a.profile.id, bedId: (await raw.bed.findFirstOrThrow({ where: { roomId: a.rooms[0].id } })).id, propertyId: a.property.id, plannedCheckIn: new Date(now + 86_400_000), plannedCheckOut: new Date(now + 2 * 86_400_000), nights: 1, createdById: 'u' } });
  await raw.stay.create({ data: { tenantId: tenantBId, studentProfileId: b.profile.id, bedId: (await raw.bed.findFirstOrThrow({ where: { roomId: b.rooms[0].id } })).id, propertyId: b.property.id, plannedCheckIn: new Date(now + 86_400_000), plannedCheckOut: new Date(now + 2 * 86_400_000), nights: 1, createdById: 'u' } });
  const onScreen = (await runAs(ctxA(), () => stays.listStays({ open: true, roomIds: [a.rooms[0].id, b.rooms[0].id] }))) as unknown[];
  assert.equal(onScreen.length, 1, 'naming B’s room does not bring B’s booking');
  const otherRoom = (await runAs(ctxA(), () => stays.listStays({ open: true, roomIds: [a.rooms[1].id] }))) as unknown[];
  assert.equal(otherRoom.length, 0, 'only the rooms named');

  // Laundry desk and batches, paged.
  for (let i = 0; i < 3; i++) await raw.laundryOrder.create({ data: { tenantId: tenantAId, propertyId: a.property.id, studentProfileId: a.profile.id, items: 2, requestedAt: new Date(now - i * 60_000) } });
  await raw.laundryOrder.create({ data: { tenantId: tenantBId, propertyId: b.property.id, studentProfileId: b.profile.id, items: 2 } });
  await raw.laundryBatch.create({ data: { tenantId: tenantAId, propertyId: a.property.id, sentById: 'u' } });
  await raw.laundryBatch.create({ data: { tenantId: tenantBId, sentById: 'u' } });
  const desk = await runAs(ctxA(), () => laundry.pageDeskOrders({ propertyId: a.property.id }, page(1, 2)));
  assert.equal(desk.total, 3);
  assert.ok(desk.items.every((o) => o.student?.id === a.profile.id), 'each bag carries its owner, all tenant A');
  assert.ok(desk.items[0].requestedAt <= desk.items[1].requestedAt, 'oldest request first, as the unpaged list');
  const batches = await runAs(ctxA(), () => laundry.pageBatches(undefined, a.property.id, page(1, 20)));
  assert.equal(batches.total, 1, 'tenant A’s batch only');
  const everyBatch = await runAs(ctxA(), () => laundry.pageBatches(undefined, undefined, page(1, 100)));
  assert.ok(everyBatch.items.every((x) => x.tenantId === tenantAId), 'no batch of tenant B with no block chosen');
  const everyPass = await runAs(ctxA(), () => gate.pagePasses(undefined, {}, page(1, 100)));
  assert.ok(everyPass.items.every((p) => p.studentProfileId !== b.profile.id), 'no pass of tenant B with no block chosen');

  // Store totals agree with the rows, and never count tenant B's store.
  const rice = await raw.messInventoryItem.create({ data: { tenantId: tenantAId, name: 'L2 Rice', unit: 'kg', reorderLevel: 1000 } });
  const dal = await raw.messInventoryItem.create({ data: { tenantId: tenantAId, name: 'L2 Dal', unit: 'kg', reorderLevel: 0 } });
  const bItem = await raw.messInventoryItem.create({ data: { tenantId: tenantBId, name: 'L2 Rice', unit: 'kg' } });
  const ymd = (daysAgo: number) => new Date(`${new Date(now - daysAgo * 86_400_000).toISOString().slice(0, 10)}T00:00:00.000Z`);
  const entry = (tenantId: string, itemId: string, direction: 'IN' | 'OUT', quantity: number, daysAgo: number, extra: { cost?: number; reason?: string | null } = {}) =>
    raw.messStockEntry.create({ data: { tenantId, itemId, direction, quantity, date: ymd(daysAgo), recordedById: 'u', ...extra } });
  await entry(tenantAId, rice.id, 'IN', 2000, 40, { cost: 1000 });
  await entry(tenantAId, rice.id, 'OUT', 500, 5, { reason: 'USAGE' });
  await entry(tenantAId, rice.id, 'OUT', 300, 3, { reason: null });
  await entry(tenantAId, rice.id, 'OUT', 400, 2, { reason: 'WASTAGE' });
  await entry(tenantAId, dal.id, 'IN', 1000, 0, { cost: 900 });
  await entry(tenantAId, dal.id, 'OUT', 100, 1, { reason: 'ADJUSTMENT' });
  await entry(tenantBId, bItem.id, 'IN', 99900, 0, { cost: 99999 });
  const totals = await runAs(ctxA(), () => inv.storeTotals());
  const rows = (await runAs(ctxA(), () => inv.listItems())) as { id: string; stockValue: number; wasted30: number; avgUnitCost: number; needsReorder: boolean; runwayDays: number | null; suggestedBuy: number | null; onHand: number }[];
  assert.equal(totals.items, rows.length);
  assert.equal(totals.stockValue, rows.reduce((n, i) => n + i.stockValue, 0), 'stock value matches the rows');
  assert.equal(totals.wastedValue, rows.reduce((n, i) => n + Math.round(i.wasted30 * i.avgUnitCost), 0), 'wastage matches the rows');
  const low = rows.filter((i) => i.needsReorder);
  assert.deepEqual(totals.shoppingList.map((i) => [i.id, i.onHand, i.runwayDays, i.suggestedBuy]), low.map((i) => [i.id, i.onHand, i.runwayDays, i.suggestedBuy]), 'the shopping list matches the rows');
  assert.ok(totals.shoppingList.some((i) => i.id === rice.id), 'rice is below its level');
  assert.ok(totals.monthSpend < 99999, 'tenant B’s purchase is not in A’s month');
});

test('Sprint L3 pages stay inside the tenant and hold the same rows as the old lists', async () => {
  const desk = await import('../modules/desk/desk.service');
  const moveouts = await import('../modules/moveouts/moveouts.service');
  const leave = await import('../modules/leave/leave.service');
  const inventory = await import('../modules/inventory/inventory.service');
  const requests = await import('../modules/requests/requests.service');
  const compliance = await import('../modules/compliance/compliance.service');
  const medical = await import('../modules/medical/medical.service');
  const events = await import('../modules/events/events.service');
  const broadcasts = await import('../modules/communication/broadcast.service');
  const gate = await import('../modules/gate/gate.service');
  const visitors = await import('../modules/gate/visitors.service');
  const page = (p: number, limit: number) => ({ page: p, limit, skip: (p - 1) * limit });
  const now = Date.now();
  const DAY = 86_400_000;

  const seed = async (tenantId: string, tag: string, n: number) => {
    const property = await raw.property.create({ data: { tenantId, name: `L3 ${tag}` } });
    const room = await raw.room.create({ data: { tenantId, propertyId: property.id, number: `L3-${tag}`, floor: 1 } });
    const admin = await raw.user.create({ data: { tenantId, role: Role.HOSTEL_ADMIN, name: `L3 admin ${tag}`, email: `l3-admin-${tag}@test.local`, passwordHash: 'x' } });
    const people = [];
    for (let i = 0; i < n; i++) {
      const u = await raw.user.create({ data: { tenantId, role: Role.STUDENT, name: `L3 ${tag} ${i}`, email: `l3-${tag}-${i}@test.local`, passwordHash: 'x' } });
      const bed = await raw.bed.create({ data: { tenantId, roomId: room.id, label: `${i}`, status: 'OCCUPIED' } });
      people.push(await raw.studentProfile.create({ data: { tenantId, userId: u.id, propertyId: property.id, bedId: bed.id, employeeCode: `E${tag}${i}` } }));
    }
    for (let i = 0; i < n; i++) {
      const p = people[i];
      await raw.parcel.create({ data: { tenantId, propertyId: property.id, studentProfileId: p.id, trackingNo: `L3${tag}${i}`, receivedAt: new Date(now - i * 60_000), receivedById: admin.id, status: i % 2 ? 'WAITING' : 'COLLECTED' } });
      await raw.lostFoundItem.create({ data: { tenantId, propertyId: property.id, kind: 'FOUND', title: `L3 ${tag} item ${i}`, happenedAt: new Date(now - i * 60_000), reportedById: admin.id } });
      await raw.moveOut.create({ data: { tenantId, studentProfileId: p.id, propertyId: property.id, lastDay: new Date(now + i * DAY), startedBy: 'OFFICE', status: i % 2 ? 'NOTICE' : 'CHECKLIST' } });
      await raw.workOrder.create({ data: { tenantId, propertyId: property.id, title: `L3 ${tag} fix ${i}`, createdById: admin.id, assigneeId: admin.id } });
      await raw.studentRequest.create({ data: { tenantId, studentProfileId: p.id, type: 'MAINTENANCE', subject: `L3 ${tag} ${i}`, body: 'x', status: 'IN_PROGRESS', assigneeId: admin.id } });
      await raw.medicalAccessLog.create({ data: { tenantId, userId: admin.id, studentProfileId: p.id, action: 'VIEW', at: new Date(now - i * 60_000) } });
      await raw.medicalAppointment.create({ data: { tenantId, studentProfileId: p.id, at: new Date(now + DAY + i * 60_000), purpose: 'Check-up', createdById: admin.id } });
      await raw.whatsAppBroadcast.create({ data: { tenantId, title: `L3 ${tag} ${i}`, body: 'x', audience: {}, createdById: admin.id, createdAt: new Date(now - i * 60_000) } });
      const item = await raw.complianceItem.create({ data: { tenantId, propertyId: property.id, kind: 'LICENCE', name: `L3 ${tag} licence ${i}`, expiresOn: new Date(now + (i % 2 ? 300 : -5) * DAY), createdById: admin.id } });
      await raw.complianceAudit.create({ data: { tenantId, entityType: 'ITEM', entityId: item.id, action: 'CREATED', actorId: admin.id, at: new Date(now - i * 60_000) } });
    }
    const inspection = await raw.complianceInspection.create({ data: { tenantId, propertyId: property.id, kind: 'INTERNAL', inspectedOn: new Date(now), inspector: `L3 ${tag}`, result: 'OBSERVATIONS', createdById: admin.id } });
    for (let i = 0; i < n; i++) await raw.complianceFinding.create({ data: { tenantId, inspectionId: inspection.id, description: `L3 ${tag} finding ${i}`, severity: 'LOW', createdAt: new Date(now - i * 1000) } });
    const leaveType = await raw.leaveType.create({ data: { tenantId, code: `L3${tag}`, name: 'Casual' } });
    for (let i = 0; i < n; i++) await raw.studentRequest.create({ data: { tenantId, studentProfileId: people[i].id, type: 'LEAVE', subject: `L3 leave ${i}`, body: 'x', leaveTypeId: leaveType.id, leaveStage: 'HOSTEL', leaveDays: 1, fromDate: new Date(now + i * DAY), toDate: new Date(now + i * DAY) } });
    const event = await raw.event.create({ data: { tenantId, propertyId: property.id, title: `L3 ${tag}`, startsAt: new Date(now + DAY), endsAt: new Date(now + DAY + 3_600_000), createdById: admin.id } });
    for (let i = 0; i < n; i++) await raw.eventRegistration.create({ data: { tenantId, eventId: event.id, studentProfileId: people[i].id, registeredAt: new Date(now - i * 60_000) } });
    return { property, admin, people, event };
  };
  const a = await seed(tenantAId, 'a', 5);
  const b = await seed(tenantBId, 'b', 3);
  const asA = <T>(fn: () => Promise<T>) => runAs({ userId: a.admin.id, role: Role.HOSTEL_ADMIN, tenantId: tenantAId }, fn);
  const viewer = { userId: a.admin.id, role: Role.HOSTEL_ADMIN, perms: ['MANAGE_GATE', 'MANAGE_STUDENTS', 'MANAGE_ROOMS'] as never[] };
  const ohc = { userId: a.admin.id, role: Role.WARDEN, perms: ['MANAGE_MEDICAL'] as never[] };
  type Pg<T> = { items: T[]; total: number; hasMore: boolean };

  /** Every page of 2, joined, is the old list in the same order — and none of it is tenant B's. */
  async function samePages<T extends { id?: string; studentProfileId?: string }>(label: string, old: () => Promise<T[]>, paged: (p: ReturnType<typeof page>) => Promise<Pg<T>>, key: (r: T) => string = (r) => r.id!) {
    const full = await asA(old);
    const pages: T[] = [];
    for (let p = 1; ; p++) {
      const got = await asA(() => paged(page(p, 2)));
      assert.equal(got.total, full.length, `${label}: the total counts the whole list`);
      pages.push(...got.items);
      if (!got.hasMore) break;
      assert.ok(p < 50, `${label}: pages end`);
    }
    assert.deepEqual(pages.map(key), full.map(key), `${label}: the pages hold the old list, in order`);
    assert.ok(full.length > 0, `${label}: tenant A has rows`);
    return pages;
  }
  const notB = (label: string, ids: string[], bIds: string[]) => assert.ok(!ids.some((id) => bIds.includes(id)), `${label}: nothing of tenant B's`);

  const parcels = await samePages('parcels', () => desk.listParcels({ propertyId: a.property.id }), (p) => desk.pageParcels({ propertyId: a.property.id }, p));
  assert.ok(parcels.every((r) => (r as { tenantId?: string }).tenantId === tenantAId), 'parcels: tenant A only');
  assert.equal((await asA(() => desk.pageParcels({ status: 'WAITING' }, page(1, 20)))).total, 2, 'parcels: the status filter counts across pages');
  await samePages('lost and found (desk)', async () => (await desk.listItems(viewer, {})) as { id: string }[], async (p) => (await desk.listItems(viewer, {}, p)) as Pg<{ id: string }>);
  const mo = await asA(() => moveouts.pageMoveOuts(undefined, undefined, page(1, 2)));
  assert.equal(mo.total, 5, 'move-outs: tenant A’s five');
  assert.deepEqual(mo.counts, { NOTICE: 2, CHECKLIST: 3 }, 'move-outs: counts per status cover every page');
  await samePages('move-outs', async () => (await moveouts.listMoveOuts()).items, (p) => moveouts.pageMoveOuts(undefined, undefined, p));
  assert.equal((await asA(() => moveouts.pageMoveOuts(undefined, ['NOTICE' as never], page(1, 20)))).total, 2, 'move-outs: one column');
  await samePages('leave approvals', async () => (await leave.queue(viewer, 'HOSTEL')) as { id: string }[], async (p) => (await leave.queue(viewer, 'HOSTEL', undefined, p)) as Pg<{ id: string }>);
  await samePages('work orders', () => inventory.listOrders(viewer, {}), (p) => inventory.pageOrders(viewer, {}, p));
  await samePages('tasks', () => requests.listAssigned(a.admin.id, true), (p) => requests.pageAssigned(a.admin.id, true, p));
  await samePages('compliance items', () => compliance.listItems({}), (p) => compliance.pageItems({}, p));
  const expired = await samePages('compliance items, expired', () => compliance.listItems({ state: 'EXPIRED' }), (p) => compliance.pageItems({ state: 'EXPIRED' }, p));
  assert.equal(expired.length, 3, 'a state is worked out before paging');
  await samePages('compliance findings', () => compliance.listFindings({}), (p) => compliance.pageFindings({}, p));
  await samePages('compliance trail', () => compliance.trail({ days: 30 }), (p) => compliance.pageTrail({ days: 30 }, p));
  await samePages('compliance trail, one block', () => compliance.trail({ days: 30, propertyId: a.property.id }), (p) => compliance.pageTrail({ days: 30, propertyId: a.property.id }, p));
  await samePages('medical access log', () => medical.accessLog({}), (p) => medical.pageAccessLog({}, p));
  await samePages('OHC people', async () => (await medical.people(ohc)) as { studentProfileId: string }[], async (p) => (await medical.people(ohc, undefined, undefined, p)) as Pg<{ studentProfileId: string }>, (r) => r.studentProfileId);
  await samePages('OHC diary', async () => (await medical.diary(ohc)) as { id: string }[], async (p) => (await medical.diary(ohc, 14, p)) as Pg<{ id: string }>);
  await samePages('events', () => events.listEvents({}), (p) => events.pageEvents({}, p));
  const sheet = await samePages('event roster', async () => (await events.roster(a.event.id)).registrations, (p) => events.pageRoster(a.event.id, undefined, p));
  assert.equal(sheet.length, 5);
  assert.equal((await asA(() => events.pageRoster(a.event.id, 'L3 a 3', page(1, 20)))).total, 1, 'the roster searches by name');
  await assert.rejects(asA(() => events.pageRoster(b.event.id, undefined, page(1, 20))), 'tenant A cannot read tenant B’s roster');
  await samePages('broadcasts', () => broadcasts.listBroadcasts(), (p) => broadcasts.pageBroadcasts(p));

  // An employee's own reports and claims, and the category filter, are asked of the server.
  const me = a.people[0];
  await raw.lostFoundItem.create({ data: { tenantId: tenantAId, propertyId: a.property.id, kind: 'LOST', title: 'L3 my phone', category: 'PHONE', happenedAt: new Date(now), reportedById: me.userId, reporterProfileId: me.id } });
  await raw.lostFoundItem.create({ data: { tenantId: tenantAId, propertyId: a.property.id, kind: 'FOUND', title: 'L3 found phone', category: 'PHONE', happenedAt: new Date(now), reportedById: a.admin.id } });
  const employee = { userId: me.userId, role: Role.STUDENT, perms: [] as never[] };
  const asMe = <T>(fn: () => Promise<T>) => runAs({ userId: me.userId, role: Role.STUDENT, tenantId: tenantAId }, fn);
  const mine = (await asMe(() => desk.listItems(employee, { mine: true }, page(1, 20)))) as Pg<{ title: string; mine: boolean }>;
  assert.deepEqual(mine.items.map((i) => i.title), ['L3 my phone'], 'mine: only their own report');
  const phones = (await asMe(() => desk.listItems(employee, { kind: 'FOUND', status: 'OPEN', category: 'PHONE' }, page(1, 20)))) as Pg<{ title: string }>;
  assert.deepEqual(phones.items.map((i) => i.title), ['L3 found phone'], 'category: found phones only');

  // The Past tab: events that are over, newest first.
  const over = await raw.event.create({ data: { tenantId: tenantAId, title: 'L3 over', startsAt: new Date(now - 2 * DAY), endsAt: new Date(now - DAY), createdById: a.admin.id } });
  await raw.event.create({ data: { tenantId: tenantBId, title: 'L3 B over', startsAt: new Date(now - 2 * DAY), endsAt: new Date(now - DAY), createdById: b.admin.id } });
  const past = await asA(() => events.pageEvents({ ended: true }, page(1, 20)));
  assert.deepEqual(past.items.map((e) => e.id), [over.id], 'ended: only tenant A’s finished event');
  assert.equal((await asA(() => events.pageRoster(a.event.id, undefined, page(1, 20), 'CANCELLED'))).total, 0, 'roster: by status');
  await samePages('tonight', async () => (await gate.tonight(a.property.id)).students, async (p) => (await gate.pageTonight(a.property.id, {}, p)) as Pg<{ studentProfileId: string }>, (r) => r.studentProfileId);
  const roll = await asA(() => gate.pageTonight(undefined, { q: 'l3 a 4' }, page(1, 20)));
  assert.deepEqual(roll.items.map((r) => r.studentProfileId), [a.people[4].id], 'tonight: search by name');
  assert.equal(roll.summary.unknown, (await asA(() => gate.tonight())).summary.unknown, 'tonight: the summary covers everyone');
  notB('tonight', (await asA(() => gate.pageTonight(undefined, {}, page(1, 100)))).items.map((r) => r.studentProfileId), b.people.map((p) => p.id));

  // The visitor export is the whole day, no longer the first 300.
  // The register's day is an India day since Sprint L4 (visitors.service dayWhere).
  const day = new Date(now).toISOString().slice(0, 10);
  const start = Date.parse(`${day}T00:00:00.000Z`);
  await raw.visitor.createMany({ data: Array.from({ length: 320 }, (_, i) => ({ tenantId: tenantAId, propertyId: a.property.id, name: `L3 visitor ${i}`, status: 'OUT', inAt: new Date(start + 1000 + i * 1000), outAt: new Date(start + 2000 + i * 1000) })) });
  await raw.visitor.create({ data: { tenantId: tenantBId, propertyId: b.property.id, name: 'L3 B visitor', status: 'OUT', inAt: new Date(start + 5000) } });
  const csv = await asA(() => visitors.visitorsCsv(a.property.id, day));
  assert.equal(csv.split('\n').length, 321, 'header and every one of the 320');
  assert.ok(!csv.includes('L3 B visitor'), 'nothing of tenant B’s in the export');
  assert.equal((await asA(() => visitors.listVisitors(a.property.id, day))).length, 300, 'the screen’s old list is unchanged');
});

test('Sprint L4 rewrites give the old answers and stay inside the tenant', async () => {
  const students = await import('../modules/students/students.service');
  const billing = await import('../modules/billing/billing.service');
  const gate = await import('../modules/gate/gate.service');
  const visitors = await import('../modules/gate/visitors.service');
  const staffAtt = await import('../modules/staff-attendance/staff-attendance.service');
  const leave = await import('../modules/leave/leave.service');
  const rooms = await import('../modules/rooms/rooms.service');
  const medical = await import('../modules/medical/medical.service');
  const requests = await import('../modules/requests/requests.service');
  const inventory = await import('../modules/inventory/inventory.service');
  const compliance = await import('../modules/compliance/compliance.service');
  const desk = await import('../modules/desk/desk.service');
  const page = (p: number, limit: number) => ({ page: p, limit, skip: (p - 1) * limit });
  const now = new Date();
  const t0 = now.getTime();
  const DAY = 86_400_000;
  const HOUR = 3_600_000;
  const IST = 330 * 60_000;
  const istDay = (ms: number) => new Date(ms + IST).toISOString().slice(0, 10);

  const seed = async (tenantId: string, tag: string, n: number) => {
    const property = await raw.property.create({ data: { tenantId, name: `L4 ${tag}` } });
    const other = await raw.property.create({ data: { tenantId, name: `L4 ${tag} 2` } });
    const room = await raw.room.create({ data: { tenantId, propertyId: property.id, number: `L4${tag}-1`, floor: 1, nightlyRent: 700 } });
    const room2 = await raw.room.create({ data: { tenantId, propertyId: other.id, number: `L4${tag}-2`, floor: 2 } });
    const planned = await raw.room.create({ data: { tenantId, propertyId: property.id, number: `L4${tag}-P`, floor: null } });
    const admin = await raw.user.create({ data: { tenantId, role: Role.HOSTEL_ADMIN, name: `L4 admin ${tag}`, email: `l4-admin-${tag}@test.local`, passwordHash: 'x' } });
    const device = await raw.biometricDevice.create({ data: { tenantId, propertyId: property.id, name: `L4 ${tag}`, serialNumber: `L4-${tag}`, apiKeyHash: `l4-${tag}` } });
    const people = [];
    for (let i = 0; i < n; i++) {
      const u = await raw.user.create({ data: { tenantId, role: Role.STUDENT, name: `L4 ${tag} person ${i}`, email: `l4-${tag}-${i}@test.local`, passwordHash: 'x' } });
      const bed = await raw.bed.create({ data: { tenantId, roomId: (i % 3 === 2 ? room2 : room).id, label: `${i}`, status: 'OCCUPIED', nightlyRent: i % 2 ? 900 : null } });
      people.push(await raw.studentProfile.create({ data: { tenantId, userId: u.id, propertyId: i % 3 === 2 ? other.id : property.id, bedId: bed.id, createdAt: new Date(t0 - (n - i) * 60_000), depositAmount: i % 4 === 0 ? null : 5000, depositPaid: i % 2 ? 5000 : 1000 } }));
    }
    // Vacant, reserved and archived beds, and one in a room with no floor.
    for (const [label, status, r, archived] of [['V1', 'VACANT', room, false], ['V2', 'VACANT', room2, false], ['R1', 'RESERVED', room, false], ['X1', 'VACANT', room, true], ['P1', 'VACANT', planned, false]] as const) {
      await raw.bed.create({ data: { tenantId, roomId: r.id, label, status, monthlyRent: label === 'V1' ? 4000 : null, archivedAt: archived ? now : null } });
    }
    // Tonight: gate punches, terminal punches (later and tied), passes out and overdue, and nobody seen.
    for (const [i, p] of people.entries()) {
      if (i % 5 === 4) continue; // never seen
      await raw.gatePunch.create({ data: { tenantId, studentProfileId: p.id, direction: i % 2 ? 'OUT' : 'IN', at: new Date(t0 - (i + 1) * HOUR) } });
      if (i % 5 === 1) await raw.biometricPunch.create({ data: { tenantId, deviceId: device.id, biometricId: `${tag}${i}`, studentProfileId: p.id, type: 'GATE_IN', punchedAt: new Date(t0 - (i + 1) * HOUR + 60_000) } });
      if (i % 5 === 3) await raw.biometricPunch.create({ data: { tenantId, deviceId: device.id, biometricId: `${tag}${i}`, studentProfileId: p.id, type: 'GATE_OUT', punchedAt: new Date(t0 - (i + 1) * HOUR) } });
      if (i % 7 === 0) await raw.gatePass.create({ data: { tenantId, studentProfileId: p.id, tokenHash: `l4-${tag}-${i}`, approvedById: admin.id, destination: 'Home', validFrom: new Date(t0 - DAY), validTo: new Date(t0 + (i % 2 ? -1 : 1) * HOUR), status: i % 2 ? 'OVERDUE' : 'OUT' } });
    }
    // Invoices with cleared, gateway and failed payments; some overdue, some due this week.
    for (const [i, p] of people.entries()) {
      for (const k of [0, 1]) {
        const inv = await raw.invoice.create({ data: { tenantId, studentProfileId: p.id, type: k ? 'MESS' : 'RENT', periodMonth: k ? '2026-10' : '2026-11', amount: 1000 + i * 10, status: i % 3 === 0 ? 'PAID' : i % 3 === 1 ? 'PARTIAL' : 'PENDING', dueDate: new Date(t0 + ((i % 9) - 4) * DAY) } });
        if (i % 3 !== 2) await raw.payment.create({ data: { tenantId, invoiceId: inv.id, amount: i % 3 === 0 ? 1000 + i * 10 : 300, method: 'UPI', status: 'CLEARED', gatewayProvider: i % 2 ? 'RAZORPAY' : null, recordedById: admin.id } });
        await raw.payment.create({ data: { tenantId, invoiceId: inv.id, amount: 50, method: 'UPI', status: 'FAILED', recordedById: admin.id } });
      }
    }
    // Staff with shifts, duties and punches over the last ten days.
    const shifts = [];
    for (const [code, st, en, off] of [['M', '06:00', '14:00', false], ['N', '22:00', '06:00', false], ['O', null, null, true]] as const) shifts.push(await raw.shift.create({ data: { tenantId, code: `L4${tag}${code}`, name: code, startTime: st, endTime: en, isOff: off } }));
    const staff = [];
    for (let i = 0; i < 4; i++) staff.push(await raw.user.create({ data: { tenantId, role: Role.WARDEN, name: `L4 staff ${tag} ${i}`, email: `l4-staff-${tag}-${i}@test.local`, passwordHash: 'x' } }));
    const days: string[] = [];
    for (let d = 9; d >= 0; d--) days.push(istDay(t0 - d * DAY));
    for (const day of days) {
      const start = Date.parse(`${day}T00:00:00.000Z`) - IST;
      for (const [i, u] of staff.entries()) {
        const sh = shifts[(i + day.charCodeAt(9)) % 3];
        await raw.staffDuty.create({ data: { tenantId, userId: u.id, date: new Date(`${day}T00:00:00.000Z`), shiftId: sh.id } });
        if (i === 3) continue; // never clocks in
        const begin = start + (sh.startTime ? Number(sh.startTime.slice(0, 2)) : 9) * HOUR + (i * 12 - 5) * 60_000;
        if (begin < t0) await raw.staffPunch.create({ data: { tenantId, userId: u.id, direction: 'IN', at: new Date(begin) } });
        if (begin + 8 * HOUR < t0 && i !== 1) await raw.staffPunch.create({ data: { tenantId, userId: u.id, direction: 'OUT', at: new Date(begin + 8 * HOUR) } });
      }
    }
    // Leave waiting at the hostel step, of a tracked and an untracked type, this year and next.
    const tracked = await raw.leaveType.create({ data: { tenantId, code: `L4T${tag}`, name: 'Casual', yearlyDays: 12, carryForwardMax: 3 } });
    const free = await raw.leaveType.create({ data: { tenantId, code: `L4F${tag}`, name: 'Unpaid', yearlyDays: null } });
    for (const [i, p] of people.entries()) {
      const type = i % 2 ? free : tracked;
      await raw.studentRequest.create({ data: { tenantId, studentProfileId: p.id, type: 'LEAVE', subject: `L4 leave ${i}`, body: 'x', status: 'OPEN', leaveTypeId: type.id, leaveStage: 'HOSTEL', leaveDays: 2, fromDate: new Date(t0 + (i % 3 === 0 ? 400 : 5) * DAY), toDate: new Date(t0 + (i % 3 === 0 ? 401 : 6) * DAY) } });
      if (i % 4 === 0) await raw.studentRequest.create({ data: { tenantId, studentProfileId: p.id, type: 'LEAVE', subject: `L4 leave ${i} done`, body: 'x', status: 'APPROVED', leaveTypeId: type.id, leaveStage: 'HOSTEL', leaveDays: 3, fromDate: new Date(t0 + 5 * DAY), toDate: new Date(t0 + 7 * DAY) } });
    }
    // Tasks, work orders and findings past due and not.
    for (let i = 0; i < 6; i++) {
      await raw.studentRequest.create({ data: { tenantId, studentProfileId: people[i % n].id, type: 'MAINTENANCE', subject: `L4 task ${i}`, body: 'x', status: i === 5 ? 'RESOLVED' : 'IN_PROGRESS', assigneeId: admin.id, dueBy: new Date(t0 + (i % 2 ? -HOUR : HOUR)) } });
      await raw.workOrder.create({ data: { tenantId, propertyId: i % 2 ? property.id : other.id, title: `L4 order ${i}`, createdById: admin.id, assigneeId: admin.id, status: i === 5 ? 'DONE' : i % 3 ? 'OPEN' : 'IN_PROGRESS', dueBy: new Date(t0 + (i % 2 ? -HOUR : HOUR)) } });
    }
    const inspection = await raw.complianceInspection.create({ data: { tenantId, propertyId: property.id, kind: 'INTERNAL', inspectedOn: now, inspector: `L4 ${tag}`, result: 'OBSERVATIONS', createdById: admin.id } });
    for (let i = 0; i < 5; i++) await raw.complianceFinding.create({ data: { tenantId, inspectionId: inspection.id, description: `L4 finding ${i}`, severity: 'LOW', status: i === 4 ? 'CLOSED' : 'OPEN', dueOn: new Date(`${istDay(t0 + (i % 2 ? -2 : 2) * DAY)}T00:00:00.000Z`) } });
    // OHC: consent given, withdrawn, none; appointments to come and past.
    for (const [i, p] of people.entries()) {
      if (i % 3 !== 2) await raw.medicalRecord.create({ data: { tenantId, studentProfileId: p.id, sealed: 'x', consentAt: i % 3 === 0 ? now : null, consentWithdrawnAt: i % 6 === 3 ? now : null, updatedById: admin.id } });
      if (i % 2 === 0) await raw.medicalAppointment.create({ data: { tenantId, studentProfileId: p.id, at: new Date(t0 + (i % 4 ? DAY : -DAY)), purpose: 'Check-up', createdById: admin.id } });
    }
    // Lost reports, and found items: by category, by a word of the title, and neither.
    await raw.lostFoundItem.create({ data: { tenantId, propertyId: property.id, kind: 'LOST', title: 'Black phone charger', category: 'ELECTRONICS', happenedAt: now, reportedById: people[0].userId, reporterProfileId: people[0].id } });
    await raw.lostFoundItem.create({ data: { tenantId, propertyId: property.id, kind: 'LOST', title: 'Blue umbrella', category: null, happenedAt: now, reportedById: people[1].userId, reporterProfileId: people[1].id } });
    for (const [i, [title, category]] of ([['Charger cable', null], ['Earphones', 'ELECTRONICS'], ['Umbrella, folding', 'OTHER'], ['Water bottle', 'OTHER'], ['Phone', null]] as [string, string | null][]).entries()) {
      await raw.lostFoundItem.create({ data: { tenantId, propertyId: i === 4 ? other.id : property.id, kind: 'FOUND', title, category, happenedAt: new Date(t0 - i * HOUR), reportedById: admin.id } });
    }
    return { property, other, admin, people, staff, days };
  };
  const a = await seed(tenantAId, 'a', 12);
  const b = await seed(tenantBId, 'b', 4);
  const ctx = { userId: a.admin.id, role: Role.HOSTEL_ADMIN, tenantId: tenantAId };
  const asA = <T>(fn: () => Promise<T>) => runAs(ctx, fn);
  const bIds = new Set([...b.people.map((p) => p.id), b.admin.id, ...b.staff.map((u) => u.id)]);

  for (const pid of [undefined, a.property.id]) {
    const where = pid ? 'one block' : 'every block';
    // studentStats.depositDue: SQL, as the rows compared in code.
    const all = await raw.studentProfile.findMany({ where: { tenantId: tenantAId, ...(pid ? { propertyId: pid } : {}), depositAmount: { not: null } }, select: { depositAmount: true, depositPaid: true } });
    const stats = await asA(() => students.studentStats(pid));
    assert.equal(stats.depositDue, all.filter((r) => (r.depositAmount ?? 0) > r.depositPaid).length, `depositDue, ${where}`);
    assert.ok(stats.depositDue > 0);

    // invoiceSummary: SQL sums, as the old loop over the rows.
    for (const f of [{}, { period: '2026-11' }, { period: '2026-10', status: 'PARTIAL' as const }, { type: 'MESS' as const }, { q: 'person 1' }, { q: '%' }, { q: '_' }, { q: 'nobody' }]) {
      const rows = await runAs(ctx, () =>
        scoped.invoice.findMany({
          where: { ...(f.period ? { periodMonth: f.period } : {}), ...(f.type ? { type: f.type } : {}), ...(f.status ? { status: f.status } : {}), ...(pid || f.q ? { student: { ...(pid ? { propertyId: pid } : {}), ...(f.q ? { user: { name: { contains: f.q, mode: 'insensitive' as const } } } : {}) } } : {}) },
          select: { id: true, amount: true, status: true, dueDate: true, payments: { where: { status: 'CLEARED' }, select: { amount: true, gatewayProvider: true } } },
        }),
      );
      const today = new Date().toISOString().slice(0, 10);
      const horizon = new Date(Date.now() + 7 * DAY).toISOString().slice(0, 10);
      const want = { billed: 0, collected: 0, collectedOnline: 0, overdueAmount: 0, overdueCount: 0, unpaidCount: 0, unpaidAmount: 0 };
      const soon: { id: string; due: string }[] = [];
      for (const inv of rows) {
        const paid = inv.payments.reduce((n, p) => n + p.amount, 0);
        want.billed += inv.amount;
        want.collected += paid;
        want.collectedOnline += inv.payments.filter((p) => p.gatewayProvider).reduce((n, p) => n + p.amount, 0);
        const due = inv.dueDate?.toISOString().slice(0, 10);
        const unpaid = inv.status !== 'PAID';
        if (unpaid && due && due < today) {
          want.overdueAmount += inv.amount - paid;
          want.overdueCount++;
        }
        if (unpaid) {
          want.unpaidCount++;
          want.unpaidAmount += Math.max(0, inv.amount - paid);
          if (due && due <= horizon) soon.push({ id: inv.id, due });
        }
      }
      const got = await asA(() => billing.invoiceSummary({ ...f, propertyId: pid }));
      assert.deepEqual({ billed: got.billed, collected: got.collected, collectedOnline: got.collectedOnline, overdueAmount: got.overdueAmount, overdueCount: got.overdueCount, unpaidCount: got.unpaidCount, unpaidAmount: got.unpaidAmount }, want, `invoiceSummary ${JSON.stringify(f)}, ${where}`);
      const ids = soon.sort((x, y) => x.due.localeCompare(y.due) || x.id.localeCompare(y.id)).slice(0, 6).map((x) => x.id);
      assert.deepEqual(got.dueSoon.map((r) => r.id), ids, `dueSoon ${JSON.stringify(f)}, ${where}`);
    }

    // Tonight in SQL: the old roll, filtered and paged in memory.
    const roll = await asA(() => gate.tonight(pid));
    assert.ok(new Set(roll.students.map((r) => r.status)).size >= 4, 'tonight: every kind of status is seeded');
    for (const f of [{}, { status: 'IN' as const }, { status: 'OUT' as const }, { status: 'OVERDUE' as const }, { status: 'UNKNOWN' as const }, { q: 'PERSON 1' }, { q: `l4a-2` }, { status: 'OUT' as const, q: 'person' }]) {
      const q = f.q?.toLowerCase();
      const want = roll.students.filter((s) => (f.status === 'OUT' ? s.status === 'OUT' || s.status === 'OUT_ON_PASS' : !f.status || s.status === f.status) && (!q || s.name.toLowerCase().includes(q) || (s.room ?? '').toLowerCase().includes(q)));
      const got = [];
      for (let p = 1; ; p++) {
        const r = await asA(() => gate.pageTonight(pid, f, page(p, 3)));
        assert.deepEqual(r.summary, roll.summary, 'tonight: the summary is the whole roll');
        assert.equal(r.total, want.length, `tonight: total ${JSON.stringify(f)}`);
        got.push(...r.items);
        if (!r.hasMore) break;
      }
      assert.deepEqual(JSON.parse(JSON.stringify(got)), JSON.parse(JSON.stringify(want)), `tonight: same rows, same order ${JSON.stringify(f)}, ${where}`);
    }
    assert.equal((await asA(() => gate.pageTonight(pid, {}, page(50, 3)))).total, roll.students.length, 'tonight: a page past the end still counts');

    // Bed choices: what the old pickers picked out of every room.
    const roomList = (await asA(() => rooms.listRooms(pid))) as { floor: number | null; number: string; beds: { id: string; status: string; label: string }[] }[];
    const vacantOld = roomList.filter((r) => r.floor != null).flatMap((r) => r.beds.filter((x) => x.status === 'VACANT').map((x) => x.id));
    const vacantNew = (await asA(() => rooms.bedChoices(pid, {}, page(1, 100)))).items.map((x) => x.id);
    assert.deepEqual([...vacantNew].sort(), [...vacantOld].sort(), `bed choices: the vacant beds of placed rooms, ${where}`);
    const anyNew = (await asA(() => rooms.bedChoices(pid, { any: true }, page(1, 100)))).items.map((x) => x.id);
    assert.deepEqual([...anyNew].sort(), roomList.filter((r) => r.floor != null).flatMap((r) => r.beds.map((x) => x.id)).sort(), `bed choices: every bed with any, ${where}`);
    const setup = await asA(() => rooms.setupCounts(pid));
    assert.deepEqual(setup, { beds: roomList.reduce((n, r) => n + r.beds.length, 0), pricedBeds: roomList.reduce((n, r) => n + r.beds.filter((x) => ((x as { monthlyRent?: number | null }).monthlyRent ?? 0) > 0).length, 0) }, `setup counts, ${where}`);
  }
  const searched = await asA(() => rooms.bedChoices(undefined, { q: 'v1' }, page(1, 20)));
  assert.deepEqual(searched.items.map((x) => x.label), ['V1'], 'bed choices: searched by bed label');
  const one = await asA(() => rooms.bedChoices(undefined, { id: a.people[0].bedId! }, page(1, 20)));
  assert.equal(one.items[0]?.status, 'OCCUPIED', 'bed choices: one bed by id, of any status');
  assert.equal((await asA(() => rooms.bedChoices(undefined, { id: b.people[0].bedId! }, page(1, 20)))).total, 0, 'bed choices: not tenant B’s bed');

  // Staff boards: one read for the run of days, the same as a board a day.
  const boards = await asA(() => staffAtt.dayBoards(a.days, now));
  for (const [i, day] of a.days.entries()) assert.deepEqual(boards[i], await asA(() => staffAtt.dayBoard(day, now)), `board ${day}`);
  assert.ok(boards.some((bd) => bd.rows.some((r) => r.status === 'LATE')) && boards.some((bd) => bd.rows.some((r) => r.status === 'ABSENT')), 'boards: late and absent days are seeded');
  assert.ok(boards.every((bd) => bd.rows.every((r) => !bIds.has(r.userId))), 'boards: nobody of tenant B’s');
  const month = a.days[a.days.length - 1].slice(0, 7);
  const monthDays = a.days.filter((d) => d.startsWith(month));
  const hours = await asA(() => staffAtt.monthHours(month, now));
  const perDay: Awaited<ReturnType<typeof staffAtt.dayBoard>>[] = [];
  for (const day of [...new Set([...Array.from({ length: 31 }, (_, i) => `${month}-${String(i + 1).padStart(2, '0')}`)])].filter((d) => d <= istDay(t0) && d.slice(8) <= '31')) {
    if (Number.isNaN(Date.parse(`${day}T00:00:00Z`)) || new Date(`${day}T00:00:00Z`).getUTCMonth() + 1 !== Number(month.slice(5))) continue;
    perDay.push(await asA(() => staffAtt.dayBoard(day, now)));
  }
  assert.ok(perDay.length >= monthDays.length);
  const want = (perDay[0]?.rows ?? []).map((s) => {
    const rs = perDay.map((bd) => bd.rows.find((r) => r.userId === s.userId)).filter((r): r is NonNullable<typeof r> => !!r);
    return { userId: s.userId, name: s.name, roleName: s.roleName ?? s.role, daysPresent: rs.filter((r) => r.firstIn).length, hours: Math.round(rs.reduce((n, r) => n + r.hours, 0) * 10) / 10, lateDays: rs.filter((r) => r.status === 'LATE').length, absences: rs.filter((r) => r.status === 'ABSENT').length };
  });
  assert.deepEqual(hours, want, 'month hours: the sum of each day’s board');

  // The leave queue: each row's balance as `balances` gives it. New allocations are made on the way.
  const approver = { userId: a.admin.id, role: Role.HOSTEL_ADMIN, perms: ['MANAGE_STUDENTS'] as never[] };
  const queued = (await asA(() => leave.queue(approver, 'HOSTEL'))) as { studentProfileId: string; leaveTypeId: string | null; fromDate: Date | null; balance: unknown }[];
  assert.ok(queued.length >= 12);
  for (const r of queued) {
    const bal = (await asA(() => leave.balances(r.studentProfileId, r.fromDate!.getUTCFullYear()))).find((x) => x.type.id === r.leaveTypeId);
    assert.deepEqual(r.balance, bal ? { available: bal.available, used: bal.used, pending: bal.pending } : null, 'leave: the row’s balance');
  }
  const pagedQueue = (await asA(() => leave.queue(approver, 'HOSTEL', undefined, page(1, 5)))) as { items: { id: string; balance: unknown }[] };
  assert.equal(pagedQueue.items.length, 5);

  // Counts across every page: tasks, work orders, findings.
  const tasks = await asA(() => requests.pageAssigned(a.admin.id, true, page(1, 1), now));
  assert.equal(tasks.overdue, (await asA(() => requests.listAssigned(a.admin.id, true))).filter((t) => t.dueBy && t.dueBy < now).length, 'tasks: overdue on every page');
  assert.ok(tasks.overdue > 0);
  const viewer = { userId: a.admin.id, role: Role.HOSTEL_ADMIN, perms: ['MANAGE_ROOMS'] as never[] };
  for (const f of [{}, { mine: true }, { propertyId: a.property.id }, { status: 'OPEN' }, { status: 'DONE' }]) {
    const orders = await asA(() => inventory.pageOrders(viewer, f, page(1, 1), now));
    const full = await asA(() => inventory.listOrders(viewer, f));
    assert.equal(orders.overdue, full.filter((w) => (w.status === 'OPEN' || w.status === 'IN_PROGRESS') && w.dueBy && w.dueBy < now).length, `work orders: overdue ${JSON.stringify(f)}`);
  }
  for (const status of [undefined, 'OPEN' as const, 'CLOSED' as const]) {
    const fp = await asA(() => compliance.pageFindings({ status }, page(1, 1), now));
    assert.equal(fp.overdue, (await asA(() => compliance.listFindings({ status }))).filter((f) => f.overdue).length, `findings: overdue ${status}`);
  }

  // The OHC people filters: the server's, the same as the chips on the unpaged list.
  const ohc = { userId: a.admin.id, role: Role.WARDEN, perms: ['MANAGE_MEDICAL'] as never[] };
  type Person = { studentProfileId: string; consent: boolean; nextAppointment: unknown };
  const everyone = (await asA(() => medical.people(ohc))) as Person[];
  for (const [filter, keep] of [['consent', (p: Person) => p.consent], ['none', (p: Person) => !p.consent], ['booked', (p: Person) => !!p.nextAppointment]] as const) {
    const got = (await asA(() => medical.people(ohc, undefined, undefined, page(1, 100), filter))) as { items: Person[]; total: number };
    assert.deepEqual(got.items.map((p) => p.studentProfileId), everyone.filter(keep).map((p) => p.studentProfileId), `OHC people: ${filter}`);
    assert.ok(got.total > 0 && got.total < everyone.length, `OHC people: ${filter} narrows`);
  }

  // Lost and found: the match hints, as the web worked them out over every open found item.
  const words = (x: string) => new Set(x.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 3));
  const deskViewer = { userId: a.admin.id, role: Role.HOSTEL_ADMIN, perms: ['MANAGE_GATE'] as never[] };
  for (const pid of [undefined, a.property.id]) {
    const lost = (await asA(() => desk.listItems(deskViewer, { kind: 'LOST', status: 'OPEN', propertyId: pid, matches: true }, page(1, 20)))) as { items: { id: string; title: string; category: string | null; matches?: { id: string }[] }[] };
    const found = (await asA(() => desk.listItems(deskViewer, { kind: 'FOUND', status: 'OPEN', propertyId: pid }))) as { id: string; title: string; category: string | null }[];
    // Ours, and the one the L3 test above reported.
    assert.ok(lost.items.length >= 2);
    for (const l of lost.items) {
      const mine = words(l.title);
      const want = found.filter((f) => (l.category && f.category === l.category) || [...words(f.title)].some((w) => mine.has(w))).slice(0, 4).map((f) => f.id);
      assert.deepEqual(l.matches?.map((m) => m.id), want, `lost and found matches: ${l.title}`);
      assert.ok(want.length > 0);
    }
  }

  // The register's day is India's: 00:30 IST is that day, 23:30 IST the same day, 00:10 IST the next.
  const day = istDay(t0 - 3 * DAY);
  const midnight = Date.parse(`${day}T00:00:00.000Z`) - IST;
  for (const [name, at] of [['L4 early', midnight + 30 * 60_000], ['L4 late', midnight + DAY - 30 * 60_000], ['L4 next', midnight + DAY + 10 * 60_000]] as const) {
    await raw.visitor.create({ data: { tenantId: tenantAId, propertyId: a.property.id, name, status: 'OUT', inAt: new Date(at), outAt: new Date(at + 60_000) } });
  }
  await raw.visitor.create({ data: { tenantId: tenantBId, propertyId: b.property.id, name: 'L4 B early', status: 'OUT', inAt: new Date(midnight + 30 * 60_000) } });
  const reg = (await asA(() => visitors.listVisitors(a.property.id, day))).map((v) => v.name).filter((n) => n.startsWith('L4'));
  assert.deepEqual(reg.sort(), ['L4 early', 'L4 late'], 'visitors: an India day');
  const regPage = await asA(() => visitors.pageVisitors(undefined, day, undefined, page(1, 50)));
  assert.deepEqual(regPage.items.map((v) => v.name).filter((n) => n.startsWith('L4')).sort(), ['L4 early', 'L4 late'], 'visitors: the paged register and its count');
  const csvDay = await asA(() => visitors.visitorsCsv(undefined, day));
  assert.ok(csvDay.includes('L4 early') && !csvDay.includes('L4 next') && !csvDay.includes('L4 B early'), 'visitors: the export is the same India day, tenant A’s');
  assert.equal(visitors.istDay(new Date(Date.parse('2026-11-07T19:00:00.000Z'))), '2026-11-08', 'visitors: 00:30 IST is already the next day');
});

/** Sprint L4: a report sheet a page at a time, searched and sorted as the web's table did it on the whole sheet. */
test('report pages: search and sort match the web viewer', async () => {
  const { pageOfRows, shownCell } = await import('../modules/reports/reports.service');
  type C = string | number | null;
  const rows: C[][] = [
    ['Asha', 12, '2026-11-04', '1 h 20 min'],
    ['bina', 2, '2026-11-04 14:30', '45 min'],
    ['Chetan 10', null, null, null],
    ['Chetan 9', 1200, '2026-01-30', '2 h'],
    ['Deepa', 2, '2026-11-03', '1 h 5 min'],
  ];
  // The web viewer's own logic (ReportViewer.tsx before Sprint L4), on the whole sheet.
  const minutes = (c: string) => {
    const m = /^(?:(\d+) h)?\s*(?:(\d+) min)?$/.exec(c);
    return m && (m[1] || m[2]) ? Number(m[1] ?? 0) * 60 + Number(m[2] ?? 0) : null;
  };
  const cmp = (a: C, b: C) => {
    if (typeof a === 'number' && typeof b === 'number') return a - b;
    const [x, y] = [String(a), String(b)];
    const [mx, my] = [minutes(x), minutes(y)];
    if (mx !== null && my !== null) return mx - my;
    return x.localeCompare(y, 'en', { numeric: true, sensitivity: 'base' });
  };
  const web = (q: string, sort: { col: number; dir: 1 | -1 } | null) => {
    const t = q.trim().toLowerCase();
    const found = t ? rows.filter((r) => r.some((c) => c !== null && (String(c).toLowerCase().includes(t) || shownCell(c).toLowerCase().includes(t)))) : rows;
    return sort ? [...found].sort((a, b) => (a[sort.col] === null || b[sort.col] === null ? Number(a[sort.col] === null) - Number(b[sort.col] === null) : cmp(a[sort.col], b[sort.col]) * sort.dir)) : found;
  };
  for (const q of ['', 'chetan', '1,200', 'nov 2026', '04 nov', 'xyz']) {
    for (const sort of [null, ...[0, 1, 2, 3].flatMap((col) => [{ col, dir: 1 as const }, { col, dir: -1 as const }])]) {
      const want = web(q, sort);
      const got: C[][] = [];
      for (let p = 1; ; p++) {
        const r = pageOfRows(rows, q || undefined, sort ?? undefined, p, 2);
        assert.equal(r.matched, want.length);
        got.push(...r.rows);
        if (!r.hasMore) break;
      }
      assert.deepEqual(got, want, `q=${q} sort=${JSON.stringify(sort)}`);
    }
  }
  assert.equal(pageOfRows(rows, undefined, undefined, 9, 2).rows.length, 0, 'a page past the end is empty');
});

test('dormitory pass and mess routes still answer, for app builds already in the store', async () => {
  const { createApp } = await import('../app');
  const { signAccessToken } = await import('../lib/jwt');
  const dorm = await raw.tenant.create({ data: { name: 'L3 Dormitory', kind: 'DORMITORY' } });
  const dormAdmin = await raw.user.create({ data: { tenantId: dorm.id, role: Role.HOSTEL_ADMIN, name: 'L3 dorm admin', email: 'l3-dorm@test.local', passwordHash: 'x' } });
  const dormGuest = await raw.user.create({ data: { tenantId: dorm.id, role: Role.STUDENT, name: 'L3 dorm guest', email: 'l3-dorm-guest@test.local', passwordHash: 'x' } });
  await raw.studentProfile.create({ data: { tenantId: dorm.id, userId: dormGuest.id } });
  const hostelAdmin = await raw.user.findFirstOrThrow({ where: { tenantId: tenantAId, role: Role.HOSTEL_ADMIN } });
  const server = createApp().listen(0);
  try {
    const port = (server.address() as { port: number }).port;
    const call = async (path: string, user: { id: string; role: Role; tenantId: string | null }) => {
      const r = await fetch(`http://127.0.0.1:${port}${path}`, { headers: { Authorization: `Bearer ${signAccessToken({ sub: user.id, role: user.role, tenantId: user.tenantId })}` } });
      return { status: r.status, code: ((await r.json().catch(() => ({}))) as { code?: string }).code };
    };
    // Builds in the store call these for a dormitory and would show an error
    // if refused. Not refused until those builds retire (the clients hide them).
    for (const path of ['/api/passes', '/api/passes?page=1', '/api/mess/menu', '/api/mess/settings', '/api/mess/calendar?period=2026-11']) {
      const r = await call(path, dormAdmin);
      assert.notEqual(r.code, 'FEATURE_OFF', `dormitory: ${path} is not refused`);
      assert.notEqual((await call(path, hostelAdmin)).status, 403, `hostel: ${path} still answers`);
    }
    assert.equal((await call('/api/passes/me', dormGuest)).status, 200, 'dormitory: a guest still reads their own (empty) passes');
    assert.equal((await call('/api/mess/menu', dormGuest)).status, 200, 'dormitory: a guest still reads the (empty) menu');
  } finally {
    server.close();
  }
});

test('teardown: drop throwaway schema', async () => {
  // The schema DATABASE_URL names, so a run against another throwaway schema
  // never drops a hc_test somebody else is using.
  const schema = new URL(process.env.DATABASE_URL ?? '').searchParams.get('schema') ?? 'hc_test';
  if (!/^hc_[a-z0-9_]+$/.test(schema)) throw new Error(`refusing to drop schema ${schema}`);
  await raw.$executeRawUnsafe(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
  await raw.$disconnect();
});
