import { Prisma, Role, type ComplianceAudit, type ComplianceFinding } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow, runWithTenantContext } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { pushTo, staffWith } from '../notifications/notifications.service';
import { paginated, type Pagination } from '../../lib/pagination';

/**
 * Statutory compliance (Sprint 7, TEPL): each block's licences, permits,
 * certificates, insurance and statutory registers, with their documents;
 * expiry dates and renewal reminders; registers reviewed on a cycle;
 * inspections and audits, their findings, and the action that closes each.
 * Keeping the records needs MANAGE_COMPLIANCE, reading them VIEW_COMPLIANCE;
 * whoever a finding is given to can see and close it. Every change, and every
 * look at a document, is kept in the audit trail.
 */

export const KINDS = ['LICENCE', 'PERMIT', 'CERTIFICATE', 'INSURANCE', 'REGISTER', 'OTHER'] as const;
export const INSPECTION_KINDS = ['STATUTORY', 'CLIENT_AUDIT', 'INTERNAL', 'MOCK_DRILL'] as const;
export const RESULTS = ['PASSED', 'OBSERVATIONS', 'FAILED'] as const;
export const SEVERITIES = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'] as const;
export type State = 'VALID' | 'DUE_SOON' | 'EXPIRED' | 'REVIEW_DUE' | 'NO_DATE' | 'ARCHIVED';

const IST_MS = 330 * 60_000;
const DAY = 86_400_000;
/** Today in India, as the UTC midnight a @db.Date column holds. */
const todayDate = (now = new Date()) => new Date(`${new Date(now.getTime() + IST_MS).toISOString().slice(0, 10)}T00:00:00.000Z`);
const ymd = (d: Date | null | undefined) => (d ? d.toISOString().slice(0, 10) : null);
/** Reminder stages, in days before expiry; each goes once, and 0 is "has expired". */
const STAGES = [60, 30, 15, 7, 1, 0];

export interface Actor {
  userId: string;
  perms: string[];
}

const canManage = (a: Actor) => a.perms.includes('MANAGE_COMPLIANCE');

// ── The standard list ───────────────────────────────────────────────────────

/**
 * What a workers' hostel in Tamil Nadu usually has to hold — our editable
 * default until TEPL's EHS team gives their own list. Dates are left empty
 * for the office to fill from the certificates.
 */
export const STANDARD_LIST: { kind: (typeof KINDS)[number]; name: string; authority: string; renewalLeadDays?: number; reviewEveryDays?: number; note?: string }[] = [
  { kind: 'LICENCE', name: 'Lodging house licence', authority: 'Local body (municipal corporation / panchayat)', renewalLeadDays: 90 },
  { kind: 'LICENCE', name: 'Trade licence', authority: 'Local body (municipal corporation / panchayat)' },
  { kind: 'LICENCE', name: 'Registration of a women’s hostel', authority: 'District Collector (Social Welfare)', renewalLeadDays: 90, note: 'Tamil Nadu Hostels and Homes for Women and Children (Regulation) Act, 2014 — for blocks housing women.' },
  { kind: 'CERTIFICATE', name: 'Fire safety certificate (Fire NOC)', authority: 'Tamil Nadu Fire and Rescue Services', renewalLeadDays: 90 },
  { kind: 'CERTIFICATE', name: 'Building stability certificate', authority: 'Chartered structural engineer', renewalLeadDays: 60 },
  { kind: 'PERMIT', name: 'Consent to operate (water and air)', authority: 'Tamil Nadu Pollution Control Board', renewalLeadDays: 90 },
  { kind: 'LICENCE', name: 'FSSAI licence (canteen)', authority: 'Food Safety and Standards Authority of India', renewalLeadDays: 60 },
  { kind: 'LICENCE', name: 'Lift licence', authority: 'Electrical Inspectorate, Government of Tamil Nadu' },
  { kind: 'CERTIFICATE', name: 'Electrical installation safety certificate', authority: 'Electrical Inspectorate, Government of Tamil Nadu' },
  { kind: 'CERTIFICATE', name: 'DG set approval', authority: 'Electrical Inspectorate, Government of Tamil Nadu' },
  { kind: 'LICENCE', name: 'Shops and Establishments registration', authority: 'Labour Department, Tamil Nadu' },
  { kind: 'LICENCE', name: 'Contract labour licence (housekeeping, security)', authority: 'Labour Department (CLRA Act)', renewalLeadDays: 45 },
  { kind: 'CERTIFICATE', name: 'Drinking water test report', authority: 'NABL-accredited laboratory', renewalLeadDays: 30, note: 'Every six months.' },
  { kind: 'CERTIFICATE', name: 'Water tank cleaning certificate', authority: 'Cleaning contractor', renewalLeadDays: 15, note: 'Every three months.' },
  { kind: 'CERTIFICATE', name: 'Pest control certificate', authority: 'Pest control contractor', renewalLeadDays: 15, note: 'Every three months.' },
  { kind: 'CERTIFICATE', name: 'Fire extinguisher refill and service', authority: 'Fire equipment contractor', renewalLeadDays: 30 },
  { kind: 'CERTIFICATE', name: 'STP treated water test', authority: 'NABL-accredited laboratory', renewalLeadDays: 30 },
  { kind: 'INSURANCE', name: 'Building and contents insurance', authority: 'Insurer', renewalLeadDays: 45 },
  { kind: 'INSURANCE', name: 'Public liability insurance', authority: 'Insurer', renewalLeadDays: 45 },
  { kind: 'REGISTER', name: 'Register of residents', authority: 'Local body / police', reviewEveryDays: 30 },
  { kind: 'REGISTER', name: 'Visitor register', authority: 'Local body / police', reviewEveryDays: 30 },
  { kind: 'REGISTER', name: 'Fire drill register', authority: 'Tamil Nadu Fire and Rescue Services', reviewEveryDays: 90 },
  { kind: 'REGISTER', name: 'First-aid register', authority: 'Factories Act (plant EHS)', reviewEveryDays: 30 },
  { kind: 'REGISTER', name: 'Accident and incident register', authority: 'Factories Act (plant EHS)', reviewEveryDays: 30 },
  { kind: 'REGISTER', name: 'Contract workers’ attendance and wages register', authority: 'Labour Department (CLRA Act)', reviewEveryDays: 30 },
];

// ── State ───────────────────────────────────────────────────────────────────

type ItemRow = Prisma.ComplianceItemGetPayload<object>;

/** Where an item stands today, and how many days are left on it. */
export function stateOf(i: Pick<ItemRow, 'archivedAt' | 'expiresOn' | 'renewalLeadDays' | 'reviewEveryDays' | 'lastReviewedAt' | 'createdAt'>, now = new Date()): { state: State; daysLeft: number | null; reviewDueOn: string | null } {
  const today = todayDate(now);
  let reviewDueOn: string | null = null;
  let reviewDue = false;
  if (i.reviewEveryDays) {
    const from = i.lastReviewedAt ?? i.createdAt;
    const due = new Date(todayDate(from).getTime() + i.reviewEveryDays * DAY);
    reviewDueOn = ymd(due);
    reviewDue = !i.lastReviewedAt || due.getTime() <= today.getTime();
  }
  if (i.archivedAt) return { state: 'ARCHIVED', daysLeft: null, reviewDueOn };
  if (i.expiresOn) {
    const daysLeft = Math.round((i.expiresOn.getTime() - today.getTime()) / DAY);
    if (daysLeft < 0) return { state: 'EXPIRED', daysLeft, reviewDueOn };
    if (daysLeft <= i.renewalLeadDays) return { state: 'DUE_SOON', daysLeft, reviewDueOn };
    return { state: reviewDue ? 'REVIEW_DUE' : 'VALID', daysLeft, reviewDueOn };
  }
  if (i.reviewEveryDays) return { state: reviewDue ? 'REVIEW_DUE' : 'VALID', daysLeft: null, reviewDueOn };
  return { state: 'NO_DATE', daysLeft: null, reviewDueOn };
}

// ── The audit trail ─────────────────────────────────────────────────────────

type Entity = 'ITEM' | 'INSPECTION' | 'FINDING';

export async function audit(actorId: string, entityType: Entity, entityId: string, action: string, changes?: Record<string, unknown>) {
  await db.complianceAudit.create({ data: { tenantId: getTenantIdOrThrow(), entityType, entityId, action, actorId, changes: (changes ?? Prisma.JsonNull) as Prisma.InputJsonValue } });
}

/** What changed, field by field, as [before, after] — dates as days. */
function diff(before: Record<string, unknown>, after: Record<string, unknown>) {
  const show = (v: unknown) => (v instanceof Date ? v.toISOString().slice(0, 10) : v ?? null);
  const out: Record<string, [unknown, unknown]> = {};
  for (const k of Object.keys(after)) if (JSON.stringify(show(before[k])) !== JSON.stringify(show(after[k]))) out[k] = [show(before[k]), show(after[k])];
  return out;
}

/** An owner change reads as names, not ids, for everyone who reads the trail. */
async function ownerNames(changes: Record<string, [unknown, unknown]>) {
  const o = changes.ownerId;
  if (!o) return changes;
  const who = await names([o[0] as string | null, o[1] as string | null]);
  const { ownerId: _o, ...rest } = changes;
  void _o;
  return { ...rest, owner: [o[0] ? who.get(o[0] as string) ?? 'someone' : null, o[1] ? who.get(o[1] as string) ?? 'someone' : null] };
}

async function names(ids: (string | null | undefined)[]) {
  const list = [...new Set(ids.filter((x): x is string => !!x))];
  if (!list.length) return new Map<string, string>();
  return new Map((await db.user.findMany({ where: { id: { in: list } }, select: { id: true, name: true } })).map((u) => [u.id, u.name]));
}

async function blockNames() {
  return new Map((await db.property.findMany({ select: { id: true, name: true } })).map((p) => [p.id, p.name]));
}

// ── Checks on what the client names ─────────────────────────────────────────

async function assertProperty(propertyId: string | null | undefined) {
  if (propertyId && !(await db.property.findFirst({ where: { id: propertyId }, select: { id: true } }))) throw new NotFoundError('Block not found');
}

async function assertStaff(userId: string | null | undefined) {
  if (userId && !(await db.user.findFirst({ where: { id: userId, role: { notIn: [Role.STUDENT, Role.SUPER_ADMIN] } }, select: { id: true } }))) throw new NotFoundError('Staff member not found');
}

/** Who can be made responsible: the office, wardens and staff logins. */
export async function owners() {
  return db.user.findMany({ where: { role: { in: [Role.HOSTEL_ADMIN, Role.WARDEN, Role.MESS_ADMIN, Role.GUARD] } }, select: { id: true, name: true, role: true, customRole: { select: { name: true } } }, orderBy: { name: 'asc' }, take: 500 });
}

// ── Items ───────────────────────────────────────────────────────────────────

export interface ItemInput {
  propertyId?: string | null;
  kind: (typeof KINDS)[number];
  name: string;
  authority?: string | null;
  referenceNo?: string | null;
  issuedOn?: Date | null;
  expiresOn?: Date | null;
  renewalLeadDays?: number;
  reviewEveryDays?: number | null;
  ownerId?: string | null;
  note?: string | null;
}

/** A block's view includes the site-wide items (no block); with no block, everything. */
const blockWhere = (propertyId?: string) => (propertyId ? { OR: [{ propertyId }, { propertyId: null }] } : {});

async function present(rows: ItemRow[]) {
  const [who, blocks] = await Promise.all([names(rows.map((r) => r.ownerId)), blockNames()]);
  const files = rows.length ? await db.attachment.groupBy({ by: ['ownerId'], where: { ownerType: 'COMPLIANCE_ITEM', ownerId: { in: rows.map((r) => r.id) } }, _count: { _all: true } }) : [];
  const fileCount = new Map(files.map((f) => [f.ownerId, f._count._all]));
  return rows.map((r) => ({
    ...r,
    issuedOn: ymd(r.issuedOn),
    expiresOn: ymd(r.expiresOn),
    ...stateOf(r),
    owner: r.ownerId ? who.get(r.ownerId) ?? null : null,
    block: r.propertyId ? blocks.get(r.propertyId) ?? null : null,
    files: fileCount.get(r.id) ?? 0,
  }));
}

type ItemFilter = { propertyId?: string; state?: State; kind?: string; q?: string; archived?: boolean };
const itemWhere = (f: ItemFilter): Prisma.ComplianceItemWhereInput => ({ ...blockWhere(f.propertyId), ...(f.kind ? { kind: f.kind } : {}), archivedAt: f.archived ? { not: null } : null, ...(f.q ? { OR: [{ name: { contains: f.q, mode: 'insensitive' } }, { referenceNo: { contains: f.q, mode: 'insensitive' } }, { authority: { contains: f.q, mode: 'insensitive' } }] } : {}) });

export async function listItems(f: ItemFilter) {
  const rows = await db.complianceItem.findMany({
    where: itemWhere(f),
    orderBy: [{ expiresOn: { sort: 'asc', nulls: 'last' } }, { name: 'asc' }],
    take: 1000,
  });
  const out = await present(rows);
  return f.state ? out.filter((r) => r.state === f.state) : out;
}

/**
 * The register a page at a time (Sprint L3), soonest expiry first as before.
 * A state is worked out from dates rather than stored, so with one asked for
 * the dates of every match are read first and only the page is dressed.
 */
export async function pageItems(f: ItemFilter, pagination: Pagination) {
  const where = itemWhere(f);
  const orderBy: Prisma.ComplianceItemOrderByWithRelationInput[] = [{ expiresOn: { sort: 'asc', nulls: 'last' } }, { name: 'asc' }, { id: 'asc' }];
  if (!f.state) {
    const [rows, total] = await Promise.all([db.complianceItem.findMany({ where, orderBy, skip: pagination.skip, take: pagination.limit }), db.complianceItem.count({ where })]);
    return paginated(await present(rows), total, pagination);
  }
  const now = new Date();
  const dates = await db.complianceItem.findMany({ where, orderBy, select: { id: true, archivedAt: true, expiresOn: true, renewalLeadDays: true, reviewEveryDays: true, lastReviewedAt: true, createdAt: true }, take: 10_000 });
  const ids = dates.filter((r) => stateOf(r, now).state === f.state).map((r) => r.id);
  const rows = await db.complianceItem.findMany({ where: { id: { in: ids.slice(pagination.skip, pagination.skip + pagination.limit) } }, orderBy });
  return paginated(await present(rows), ids.length, pagination);
}

export async function getItem(id: string) {
  const row = await db.complianceItem.findFirst({ where: { id } });
  if (!row) throw new NotFoundError('Not found');
  const [item] = await present([row]);
  const [inspections, trail] = await Promise.all([
    listInspections({ itemId: id }),
    db.complianceAudit.findMany({ where: { entityType: 'ITEM', entityId: id }, orderBy: { at: 'desc' }, take: 100 }),
  ]);
  const who = await names(trail.map((t) => t.actorId));
  return {
    item,
    inspections: inspections.slice(0, 20),
    trail: trail.map((t) => ({ ...t, actor: who.get(t.actorId) ?? null })),
  };
}

/** Only the fields an item takes from outside, whatever else the caller passed. */
function pickItem(i: Partial<ItemInput>) {
  const keys = ['propertyId', 'kind', 'name', 'authority', 'referenceNo', 'issuedOn', 'expiresOn', 'renewalLeadDays', 'reviewEveryDays', 'ownerId', 'note'] as const;
  return Object.fromEntries(keys.filter((k) => i[k] !== undefined).map((k) => [k, i[k]])) as Partial<ItemInput>;
}

function checkDates(issuedOn: Date | null | undefined, expiresOn: Date | null | undefined) {
  if (issuedOn && expiresOn && expiresOn < issuedOn) throw new BadRequestError('The expiry date is before the issue date');
}

export async function createItem(input: ItemInput, actorId: string) {
  await Promise.all([assertProperty(input.propertyId), assertStaff(input.ownerId)]);
  checkDates(input.issuedOn, input.expiresOn);
  const row = await db.complianceItem.create({ data: { tenantId: getTenantIdOrThrow(), ...pickItem(input), kind: input.kind, name: input.name, propertyId: input.propertyId ?? null, createdById: actorId } });
  await audit(actorId, 'ITEM', row.id, 'CREATED', { name: row.name, kind: row.kind, expiresOn: ymd(row.expiresOn) });
  return (await present([row]))[0];
}

export async function updateItem(id: string, input: Partial<ItemInput>, actorId: string) {
  const before = await db.complianceItem.findFirst({ where: { id } });
  if (!before) throw new NotFoundError('Not found');
  await Promise.all([assertProperty(input.propertyId), assertStaff(input.ownerId)]);
  checkDates(input.issuedOn === undefined ? before.issuedOn : input.issuedOn, input.expiresOn === undefined ? before.expiresOn : input.expiresOn);
  const moved = input.expiresOn !== undefined && ymd(input.expiresOn) !== ymd(before.expiresOn);
  const row = await db.complianceItem.update({ where: { id }, data: { ...pickItem(input), ...(moved ? { remindedStage: null } : {}) } });
  const changes = await ownerNames(diff(before as unknown as Record<string, unknown>, input as Record<string, unknown>));
  if (Object.keys(changes).length) await audit(actorId, 'ITEM', id, 'UPDATED', changes);
  return (await present([row]))[0];
}

/** A renewal: the new certificate's dates and number; reminders start over. */
export async function renewItem(id: string, input: { issuedOn?: Date | null; expiresOn: Date; referenceNo?: string | null; note?: string | null }, actorId: string) {
  const before = await db.complianceItem.findFirst({ where: { id } });
  if (!before) throw new NotFoundError('Not found');
  if (before.archivedAt) throw new ConflictError('This item is archived');
  checkDates(input.issuedOn, input.expiresOn);
  if (before.expiresOn && input.expiresOn <= before.expiresOn) throw new BadRequestError('The new expiry date must be after the current one');
  const data = { issuedOn: input.issuedOn ?? before.issuedOn, expiresOn: input.expiresOn, referenceNo: input.referenceNo ?? before.referenceNo, renewalStartedAt: null, remindedStage: null };
  const row = await db.complianceItem.update({ where: { id }, data });
  await audit(actorId, 'ITEM', id, 'RENEWED', { ...diff(before as unknown as Record<string, unknown>, data), ...(input.note ? { note: input.note } : {}) });
  return (await present([row]))[0];
}

/** Renewal applied for: shown as in hand, so nobody chases it twice. */
export async function startRenewal(id: string, actorId: string) {
  const before = await db.complianceItem.findFirst({ where: { id } });
  if (!before) throw new NotFoundError('Not found');
  if (before.renewalStartedAt) throw new ConflictError('Renewal is already in hand');
  const row = await db.complianceItem.update({ where: { id }, data: { renewalStartedAt: new Date() } });
  await audit(actorId, 'ITEM', id, 'RENEWAL_STARTED');
  return (await present([row]))[0];
}

/** A register checked and up to date. */
export async function markReviewed(id: string, note: string | null | undefined, actorId: string) {
  const before = await db.complianceItem.findFirst({ where: { id } });
  if (!before) throw new NotFoundError('Not found');
  if (!before.reviewEveryDays) throw new BadRequestError('This item has no review cycle');
  const row = await db.complianceItem.update({ where: { id }, data: { lastReviewedAt: new Date(), reviewRemindedAt: null } });
  await audit(actorId, 'ITEM', id, 'REVIEWED', note ? { note } : undefined);
  return (await present([row]))[0];
}

export async function archiveItem(id: string, archived: boolean, actorId: string) {
  const before = await db.complianceItem.findFirst({ where: { id } });
  if (!before) throw new NotFoundError('Not found');
  if (!!before.archivedAt === archived) throw new ConflictError(archived ? 'Already archived' : 'Not archived');
  const row = await db.complianceItem.update({ where: { id }, data: { archivedAt: archived ? new Date() : null } });
  await audit(actorId, 'ITEM', id, archived ? 'ARCHIVED' : 'RESTORED');
  return (await present([row]))[0];
}

/** Adds the standard list to a block (or the site), skipping names it already has. */
export async function loadStandardList(propertyId: string | null, actorId: string) {
  await assertProperty(propertyId);
  const have = new Set((await db.complianceItem.findMany({ where: { propertyId }, select: { name: true } })).map((r) => r.name.toLowerCase()));
  const tenantId = getTenantIdOrThrow();
  const fresh = STANDARD_LIST.filter((s) => !have.has(s.name.toLowerCase()));
  for (const s of fresh) {
    const row = await db.complianceItem.create({ data: { tenantId, propertyId, kind: s.kind, name: s.name, authority: s.authority, renewalLeadDays: s.renewalLeadDays ?? 60, reviewEveryDays: s.reviewEveryDays ?? null, note: s.note ?? null, createdById: actorId } });
    await audit(actorId, 'ITEM', row.id, 'CREATED', { name: row.name, from: 'standard list' });
  }
  return { added: fresh.length, skipped: STANDARD_LIST.length - fresh.length };
}

// ── Inspections and findings ────────────────────────────────────────────────

export interface InspectionInput {
  propertyId?: string | null;
  itemId?: string | null;
  kind: (typeof INSPECTION_KINDS)[number];
  inspectedOn: Date;
  inspector: string;
  result: (typeof RESULTS)[number];
  summary?: string | null;
  findings?: { description: string; severity: (typeof SEVERITIES)[number]; ownerId?: string | null; dueOn?: Date | null }[];
}

export async function createInspection(input: InspectionInput, actorId: string) {
  await assertProperty(input.propertyId);
  if (input.itemId && !(await db.complianceItem.findFirst({ where: { id: input.itemId }, select: { id: true } }))) throw new NotFoundError('Item not found');
  if (input.inspectedOn > todayDate()) throw new BadRequestError('An inspection cannot be in the future');
  const findings = input.findings ?? [];
  for (const f of findings) await assertStaff(f.ownerId);
  const tenantId = getTenantIdOrThrow();
  const ins = await db.complianceInspection.create({ data: { tenantId, propertyId: input.propertyId ?? null, itemId: input.itemId ?? null, kind: input.kind, inspectedOn: input.inspectedOn, inspector: input.inspector, result: input.result, summary: input.summary ?? null, createdById: actorId } });
  await audit(actorId, 'INSPECTION', ins.id, 'CREATED', { inspector: ins.inspector, result: ins.result, inspectedOn: ymd(ins.inspectedOn), findings: findings.length });
  const made = [];
  for (const f of findings) {
    const row = await db.complianceFinding.create({ data: { tenantId, inspectionId: ins.id, description: f.description, severity: f.severity, ownerId: f.ownerId ?? null, dueOn: f.dueOn ?? null } });
    await audit(actorId, 'FINDING', row.id, 'CREATED', { severity: row.severity, dueOn: ymd(row.dueOn) });
    made.push(row);
  }
  if (made.length) notifyOwners(tenantId, made);
  return getInspection(ins.id);
}

function notifyOwners(tenantId: string, findings: { id: string; ownerId: string | null; description: string; dueOn: Date | null }[]) {
  for (const f of findings) {
    if (!f.ownerId) continue;
    void pushTo(tenantId, 'COMPLIANCE_ACTION', f.id, [f.ownerId], { title: 'A compliance action is yours', body: `${f.description.slice(0, 120)}${f.dueOn ? ` · by ${ymd(f.dueOn)}` : ''}`, data: { findingId: f.id } }).catch((err) => console.error('[push] compliance action failed:', err)); // eslint-disable-line no-console
  }
}

async function presentFindings<T extends { ownerId: string | null; closedById: string | null; dueOn: Date | null; status: string }>(rows: T[]) {
  const who = await names(rows.flatMap((r) => [r.ownerId, r.closedById]));
  const today = todayDate();
  return rows.map((r) => ({ ...r, dueOn: ymd(r.dueOn), overdue: r.status === 'OPEN' && !!r.dueOn && r.dueOn < today, owner: r.ownerId ? who.get(r.ownerId) ?? null : null, closedBy: r.closedById ? who.get(r.closedById) ?? null : null }));
}

export async function listInspections(f: { propertyId?: string; from?: Date; to?: Date; itemId?: string }) {
  const rows = await db.complianceInspection.findMany({
    where: { ...blockWhere(f.propertyId), ...(f.itemId ? { itemId: f.itemId } : {}), ...(f.from || f.to ? { inspectedOn: { ...(f.from ? { gte: f.from } : {}), ...(f.to ? { lte: f.to } : {}) } } : {}) },
    orderBy: { inspectedOn: 'desc' },
    take: 300,
  });
  const counts = rows.length ? await db.complianceFinding.groupBy({ by: ['inspectionId', 'status'], where: { inspectionId: { in: rows.map((r) => r.id) } }, _count: { _all: true } }) : [];
  const [blocks, items] = await Promise.all([blockNames(), db.complianceItem.findMany({ where: { id: { in: rows.map((r) => r.itemId).filter((x): x is string => !!x) } }, select: { id: true, name: true } })]);
  const itemName = new Map(items.map((i) => [i.id, i.name]));
  return rows.map((r) => ({
    ...r,
    inspectedOn: ymd(r.inspectedOn),
    block: r.propertyId ? blocks.get(r.propertyId) ?? null : null,
    item: r.itemId ? itemName.get(r.itemId) ?? null : null,
    open: counts.find((c) => c.inspectionId === r.id && c.status === 'OPEN')?._count._all ?? 0,
    closed: counts.find((c) => c.inspectionId === r.id && c.status === 'CLOSED')?._count._all ?? 0,
  }));
}

export async function getInspection(id: string) {
  const ins = await db.complianceInspection.findFirst({ where: { id } });
  if (!ins) throw new NotFoundError('Not found');
  const [findings, trail, blocks, item] = await Promise.all([
    db.complianceFinding.findMany({ where: { inspectionId: id }, orderBy: [{ status: 'asc' }, { dueOn: { sort: 'asc', nulls: 'last' } }] }),
    db.complianceAudit.findMany({ where: { entityType: 'INSPECTION', entityId: id }, orderBy: { at: 'desc' }, take: 50 }),
    blockNames(),
    ins.itemId ? db.complianceItem.findFirst({ where: { id: ins.itemId }, select: { id: true, name: true } }) : null,
  ]);
  const who = await names([ins.createdById, ...trail.map((t) => t.actorId)]);
  return {
    inspection: { ...ins, inspectedOn: ymd(ins.inspectedOn), block: ins.propertyId ? blocks.get(ins.propertyId) ?? null : null, item: item?.name ?? null, recordedBy: who.get(ins.createdById) ?? null },
    findings: await presentFindings(findings),
    trail: trail.map((t) => ({ ...t, actor: who.get(t.actorId) ?? null })),
  };
}

export async function addFinding(inspectionId: string, f: { description: string; severity: (typeof SEVERITIES)[number]; ownerId?: string | null; dueOn?: Date | null }, actorId: string) {
  if (!(await db.complianceInspection.findFirst({ where: { id: inspectionId }, select: { id: true } }))) throw new NotFoundError('Inspection not found');
  await assertStaff(f.ownerId);
  const tenantId = getTenantIdOrThrow();
  const row = await db.complianceFinding.create({ data: { tenantId, inspectionId, description: f.description, severity: f.severity, ownerId: f.ownerId ?? null, dueOn: f.dueOn ?? null } });
  await audit(actorId, 'FINDING', row.id, 'CREATED', { severity: row.severity, dueOn: ymd(row.dueOn) });
  notifyOwners(tenantId, [row]);
  return (await presentFindings([row]))[0];
}

type FindingFilter = { propertyId?: string; status?: 'OPEN' | 'CLOSED'; ownerId?: string };
async function findingWhere(f: FindingFilter): Promise<Prisma.ComplianceFindingWhereInput> {
  const inspections = f.propertyId ? (await db.complianceInspection.findMany({ where: blockWhere(f.propertyId), select: { id: true } })).map((i) => i.id) : null;
  return { ...(f.status ? { status: f.status } : {}), ...(f.ownerId ? { ownerId: f.ownerId } : {}), ...(inspections ? { inspectionId: { in: inspections } } : {}) };
}

/** Open findings, overdue first; or everything, or only one person's. */
export async function listFindings(f: FindingFilter) {
  const rows = await db.complianceFinding.findMany({
    where: await findingWhere(f),
    orderBy: [{ status: 'asc' }, { dueOn: { sort: 'asc', nulls: 'last' } }, { createdAt: 'asc' }],
    take: 1000,
  });
  return dressFindings(rows);
}

/**
 * Findings a page at a time (Sprint L3), in the same order; the id breaks ties.
 * `overdue` (Sprint L4) counts the open ones past their due day under the same
 * filter, on every page: the rule each row's own `overdue` follows.
 */
export async function pageFindings(f: FindingFilter, pagination: Pagination, now = new Date()) {
  const where = await findingWhere(f);
  const open = !f.status || f.status === 'OPEN';
  const [rows, total, overdue] = await Promise.all([
    db.complianceFinding.findMany({ where, orderBy: [{ status: 'asc' }, { dueOn: { sort: 'asc', nulls: 'last' } }, { createdAt: 'asc' }, { id: 'asc' }], skip: pagination.skip, take: pagination.limit }),
    db.complianceFinding.count({ where }),
    open ? db.complianceFinding.count({ where: { ...where, status: 'OPEN', dueOn: { lt: todayDate(now) } } }) : Promise.resolve(0),
  ]);
  return { ...paginated(await dressFindings(rows), total, pagination), overdue };
}

async function dressFindings(rows: ComplianceFinding[]) {
  const ins = new Map((await db.complianceInspection.findMany({ where: { id: { in: [...new Set(rows.map((r) => r.inspectionId))] } }, select: { id: true, inspector: true, inspectedOn: true, kind: true, propertyId: true } })).map((i) => [i.id, i]));
  const blocks = await blockNames();
  return (await presentFindings(rows)).map((r) => {
    const i = ins.get(r.inspectionId);
    return { ...r, inspection: i ? { id: i.id, inspector: i.inspector, inspectedOn: ymd(i.inspectedOn), kind: i.kind, block: i.propertyId ? blocks.get(i.propertyId) ?? null : null } : null };
  });
}

async function findingFor(id: string, actor: Actor) {
  const f = await db.complianceFinding.findFirst({ where: { id } });
  // Not found rather than forbidden for someone it was not given to.
  if (!f || (!canManage(actor) && f.ownerId !== actor.userId)) throw new NotFoundError('Not found');
  return f;
}

export async function updateFinding(id: string, input: { description?: string; severity?: (typeof SEVERITIES)[number]; ownerId?: string | null; dueOn?: Date | null }, actorId: string) {
  const before = await db.complianceFinding.findFirst({ where: { id } });
  if (!before) throw new NotFoundError('Not found');
  if (before.status !== 'OPEN') throw new ConflictError('This finding is closed');
  await assertStaff(input.ownerId);
  const row = await db.complianceFinding.update({ where: { id }, data: { ...input, ...(input.dueOn !== undefined ? { overdueNotifiedAt: null } : {}) } });
  const changes = await ownerNames(diff(before as unknown as Record<string, unknown>, input as Record<string, unknown>));
  if (Object.keys(changes).length) await audit(actorId, 'FINDING', id, 'UPDATED', changes);
  if (input.ownerId && input.ownerId !== before.ownerId) notifyOwners(getTenantIdOrThrow(), [row]);
  return (await presentFindings([row]))[0];
}

/** Closed with what was done — by the compliance desk, or the person it was given to. */
export async function closeFinding(id: string, note: string, actor: Actor) {
  const f = await findingFor(id, actor);
  if (f.status !== 'OPEN') throw new ConflictError('Already closed');
  const row = await db.complianceFinding.update({ where: { id }, data: { status: 'CLOSED', closedAt: new Date(), closedById: actor.userId, closureNote: note } });
  await audit(actor.userId, 'FINDING', id, 'CLOSED', { note });
  return (await presentFindings([row]))[0];
}

export async function reopenFinding(id: string, reason: string, actorId: string) {
  const f = await db.complianceFinding.findFirst({ where: { id } });
  if (!f) throw new NotFoundError('Not found');
  if (f.status !== 'CLOSED') throw new ConflictError('This finding is open');
  const row = await db.complianceFinding.update({ where: { id }, data: { status: 'OPEN', closedAt: null, closedById: null, closureNote: null, overdueNotifiedAt: null } });
  await audit(actorId, 'FINDING', id, 'REOPENED', { reason });
  return (await presentFindings([row]))[0];
}

/** For anyone a finding was given to: theirs, with the inspection it came from. */
export async function myActions(userId: string) {
  return listFindings({ ownerId: userId });
}

export async function findingTrail(id: string, actor: Actor) {
  await findingFor(id, actor);
  const trail = await db.complianceAudit.findMany({ where: { entityType: 'FINDING', entityId: id }, orderBy: { at: 'desc' }, take: 50 });
  const who = await names(trail.map((t) => t.actorId));
  return trail.map((t) => ({ ...t, actor: who.get(t.actorId) ?? null }));
}

// ── Dashboard and the trail ─────────────────────────────────────────────────

const emptyCounts = () => ({ total: 0, VALID: 0, DUE_SOON: 0, EXPIRED: 0, REVIEW_DUE: 0, NO_DATE: 0 });

export async function dashboard(propertyId?: string) {
  const [items, findings, inspections, properties] = await Promise.all([
    listItems({ propertyId }),
    listFindings({ propertyId, status: 'OPEN' }),
    listInspections({ propertyId, from: new Date(todayDate().getTime() - 365 * DAY) }),
    db.property.findMany({ where: { isArchived: false, ...(propertyId ? { id: propertyId } : {}) }, select: { id: true, name: true }, orderBy: { name: 'asc' } }),
  ]);
  const tally = (rows: typeof items) => {
    const c = emptyCounts();
    for (const r of rows) {
      c.total++;
      if (r.state !== 'ARCHIVED') c[r.state]++;
    }
    // In order: everything dated and in date, out of everything that can be.
    const scored = c.total - c.NO_DATE;
    return { ...c, score: scored ? Math.round(((c.VALID + c.REVIEW_DUE + c.DUE_SOON) / scored) * 100) : null };
  };
  const blocks = [
    ...properties.map((p) => ({ propertyId: p.id, name: p.name, ...tally(items.filter((i) => i.propertyId === p.id)) })),
    { propertyId: null, name: 'Whole site', ...tally(items.filter((i) => i.propertyId === null)) },
  ];
  const sev = (s: string) => findings.filter((f) => f.severity === s).length;
  return {
    totals: tally(items),
    blocks,
    findings: { open: findings.length, overdue: findings.filter((f) => f.overdue).length, critical: sev('CRITICAL'), high: sev('HIGH'), medium: sev('MEDIUM'), low: sev('LOW') },
    upcoming: items.filter((i) => i.state === 'EXPIRED' || i.state === 'DUE_SOON' || (i.daysLeft !== null && i.daysLeft <= 90)).slice(0, 15),
    reviewsDue: items.filter((i) => i.state === 'REVIEW_DUE').slice(0, 15),
    overdueFindings: findings.filter((f) => f.overdue).slice(0, 15),
    recentInspections: inspections.slice(0, 8),
    lastInspection: inspections[0]?.inspectedOn ?? null,
  };
}

export async function trail(f: { entityType?: Entity; days: number; propertyId?: string }) {
  const rows = await db.complianceAudit.findMany({ where: { ...(f.entityType ? { entityType: f.entityType } : {}), at: { gte: new Date(Date.now() - f.days * DAY) } }, orderBy: { at: 'desc' }, take: 500 });
  return dressTrail(rows, f.propertyId);
}

/**
 * The trail a page at a time (Sprint L3), newest first. A block's trail holds
 * its own records and the whole-site ones, so the records of every other
 * block are left out in the query rather than after it, or a page would come
 * back short.
 */
export async function pageTrail(f: { entityType?: Entity; days: number; propertyId?: string }, pagination: Pagination) {
  let elsewhere: string[] = [];
  if (f.propertyId) {
    const other = { propertyId: { not: null, notIn: [f.propertyId] } };
    const [items, inspections] = await Promise.all([db.complianceItem.findMany({ where: other, select: { id: true } }), db.complianceInspection.findMany({ where: other, select: { id: true } })]);
    const findings = inspections.length ? await db.complianceFinding.findMany({ where: { inspectionId: { in: inspections.map((i) => i.id) } }, select: { id: true } }) : [];
    elsewhere = [...items, ...inspections, ...findings].map((x) => x.id);
  }
  const where: Prisma.ComplianceAuditWhereInput = { ...(f.entityType ? { entityType: f.entityType } : {}), at: { gte: new Date(Date.now() - f.days * DAY) }, ...(elsewhere.length ? { entityId: { notIn: elsewhere } } : {}) };
  const [rows, total] = await Promise.all([
    db.complianceAudit.findMany({ where, orderBy: [{ at: 'desc' }, { id: 'asc' }], skip: pagination.skip, take: pagination.limit }),
    db.complianceAudit.count({ where }),
  ]);
  return paginated(await dressTrail(rows), total, pagination);
}

/** Names, subjects and parents for trail rows; with a block, rows from other blocks are dropped. */
async function dressTrail(rows: ComplianceAudit[], propertyId?: string) {
  const f = { propertyId };
  const who = await names(rows.map((r) => r.actorId));
  const [items, inspections, findings] = await Promise.all([
    db.complianceItem.findMany({ where: { id: { in: rows.filter((r) => r.entityType === 'ITEM').map((r) => r.entityId) } }, select: { id: true, name: true, propertyId: true } }),
    db.complianceInspection.findMany({ where: { id: { in: rows.filter((r) => r.entityType === 'INSPECTION').map((r) => r.entityId) } }, select: { id: true, inspector: true, inspectedOn: true, propertyId: true } }),
    db.complianceFinding.findMany({ where: { id: { in: rows.filter((r) => r.entityType === 'FINDING').map((r) => r.entityId) } }, select: { id: true, description: true, inspectionId: true } }),
  ]);
  // A finding belongs to its inspection's block.
  const parents = new Map((await db.complianceInspection.findMany({ where: { id: { in: findings.map((x) => x.inspectionId) } }, select: { id: true, propertyId: true } })).map((i) => [i.id, i.propertyId]));
  const label = new Map<string, string>([...items.map((i) => [i.id, i.name] as const), ...inspections.map((i) => [i.id, `${i.inspector} · ${ymd(i.inspectedOn)}`] as const), ...findings.map((x) => [x.id, x.description.slice(0, 80)] as const)]);
  const block = new Map<string, string | null>([...items.map((i) => [i.id, i.propertyId] as const), ...inspections.map((i) => [i.id, i.propertyId] as const), ...findings.map((x) => [x.id, parents.get(x.inspectionId) ?? null] as const)]);
  const inspectionOf = new Map(findings.map((x) => [x.id, x.inspectionId]));
  // A block's trail holds its own records and the whole-site ones, like its lists.
  const inBlock = (r: (typeof rows)[number]) => !f.propertyId || !block.has(r.entityId) || block.get(r.entityId) === null || block.get(r.entityId) === f.propertyId;
  return rows.filter(inBlock).map((r) => ({ ...r, actor: who.get(r.actorId) ?? null, subject: label.get(r.entityId) ?? null, inspectionId: inspectionOf.get(r.entityId) ?? null }));
}

// ── Reminders (hourly) ──────────────────────────────────────────────────────

/** The stage an item has reached: the smallest stage at or above its days left. */
function stageFor(daysLeft: number, lead: number) {
  const stages = STAGES.filter((s) => s === 0 || s <= lead);
  let stage: number | null = null;
  for (const s of stages) if (daysLeft <= s) stage = s;
  return daysLeft < 0 ? 0 : stage;
}

/**
 * Each notice has its own reference (item and stage, register and day, action
 * and due date), as the inbox and the push log keep one per person, kind and
 * reference — so a later stage is not swallowed by an earlier one.
 *
 * Hourly: an expiring item reminds its owner and the compliance desk at 60,
 * 30, 15, 7 and 1 days (those inside its lead time) and once when it lapses;
 * a register due a review reminds once per cycle; an action past its date
 * reminds its owner once.
 */
export async function runCompliancePass(now = new Date()) {
  const tenants = await prismaUnscoped.complianceItem.findMany({ where: { archivedAt: null }, distinct: ['tenantId'], select: { tenantId: true } });
  const withFindings = await prismaUnscoped.complianceFinding.findMany({ where: { status: 'OPEN' }, distinct: ['tenantId'], select: { tenantId: true } });
  let sent = 0;
  for (const tenantId of new Set([...tenants, ...withFindings].map((t) => t.tenantId))) {
    if (!(await tenantHasFeature(tenantId, 'compliance'))) continue;
    sent += await runWithTenantContext({ userId: 'system:compliance', role: Role.HOSTEL_ADMIN, tenantId }, () => passFor(tenantId, now));
  }
  return sent;
}

/** The desk's "check now": this account's reminders, outside the hourly tick. */
export async function runCompliancePassNow(now = new Date()) {
  return { sent: await passFor(getTenantIdOrThrow(), now) };
}

async function passFor(tenantId: string, now: Date) {
  const desk = await staffWith(tenantId, 'MANAGE_COMPLIANCE');
  const to = (ownerId: string | null) => [...new Set([...(ownerId ? [ownerId] : []), ...desk])];
  const blocks = await blockNames();
  const where = (p: string | null) => (p ? ` · ${blocks.get(p) ?? 'block'}` : '');
  let sent = 0;
  const today = todayDate(now);

  const items = await db.complianceItem.findMany({ where: { archivedAt: null, OR: [{ expiresOn: { not: null } }, { reviewEveryDays: { not: null } }] }, take: 5000 });
  for (const i of items) {
    if (i.expiresOn) {
      const daysLeft = Math.round((i.expiresOn.getTime() - today.getTime()) / DAY);
      const stage = stageFor(daysLeft, i.renewalLeadDays);
      if (stage !== null && (i.remindedStage === null || stage < i.remindedStage)) {
        await db.complianceItem.update({ where: { id: i.id }, data: { remindedStage: stage } });
        const title = daysLeft < 0 ? `Expired: ${i.name}` : daysLeft === 0 ? `Expires today: ${i.name}` : `${i.name} expires in ${daysLeft} day${daysLeft === 1 ? '' : 's'}`;
        const body = `${i.renewalStartedAt ? 'Renewal in hand' : 'Renewal not started'} · ${ymd(i.expiresOn)}${where(i.propertyId)}`;
        await pushTo(tenantId, 'COMPLIANCE_DUE', `${i.id}:${ymd(i.expiresOn)}:${stage}`, to(i.ownerId), { title, body, data: { complianceItemId: i.id } }).catch((err) => console.error('[push] compliance due failed:', err)); // eslint-disable-line no-console
        sent++;
      }
    }
    if (i.reviewEveryDays) {
      const { state, reviewDueOn } = stateOf(i, now);
      const dueAgain = !i.reviewRemindedAt || i.reviewRemindedAt.getTime() + i.reviewEveryDays * DAY <= now.getTime();
      if ((state === 'REVIEW_DUE' || (reviewDueOn && reviewDueOn <= ymd(today)!)) && dueAgain) {
        await db.complianceItem.update({ where: { id: i.id }, data: { reviewRemindedAt: now } });
        await pushTo(tenantId, 'COMPLIANCE_DUE', `${i.id}:review:${ymd(today)}`, to(i.ownerId), { title: `Review due: ${i.name}`, body: `Check it is up to date and mark it reviewed${where(i.propertyId)}`, data: { complianceItemId: i.id } }).catch((err) => console.error('[push] compliance review failed:', err)); // eslint-disable-line no-console
        sent++;
      }
    }
  }

  const overdue = await db.complianceFinding.findMany({ where: { status: 'OPEN', dueOn: { lt: today }, overdueNotifiedAt: null }, take: 1000 });
  for (const f of overdue) {
    await db.complianceFinding.update({ where: { id: f.id }, data: { overdueNotifiedAt: now } });
    await pushTo(tenantId, 'COMPLIANCE_ACTION', `${f.id}:overdue:${ymd(f.dueOn)}:${now.getTime()}`, to(f.ownerId), { title: 'Compliance action overdue', body: `${f.description.slice(0, 120)} · was due ${ymd(f.dueOn)}`, data: { findingId: f.id } }).catch((err) => console.error('[push] compliance overdue failed:', err)); // eslint-disable-line no-console
    sent++;
  }
  return sent;
}
