import { Prisma, Role } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, ForbiddenError, NotFoundError } from '../../lib/errors';
import type { Permission } from '../../lib/permissions';
import { medicalContext, openJson, sealJson } from '../../lib/medicalCrypto';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { pushTo } from '../notifications/notifications.service';
import { ohcLogins } from './medical-access';
import { paginated, type Pagination } from '../../lib/pagination';

/**
 * Medical records (Sprint 6, TEPL), kept by the occupational health centre.
 *
 * - Only OHC staff open them: a staff login whose role carries "Medical
 *   records". The hostel's owner does not — they see who looked, not what.
 * - Everything clinical is sealed (AES-GCM, its own key) in the database.
 * - The employee gives consent (in the app, or on a signed form the OHC
 *   records); without it the record cannot be written, though a visit can.
 * - Every look and every change is logged; the employee sees their own log.
 * - Appointments remind the employee the day before, without saying why.
 */

export interface Viewer {
  userId: string;
  role: Role;
  perms: Permission[];
}

export const isOhc = (v: Viewer) => v.role !== Role.HOSTEL_ADMIN && v.perms.includes('MANAGE_MEDICAL');
export function assertOhc(v: Viewer) {
  if (!isOhc(v)) throw new ForbiddenError('Only OHC staff can open medical records');
}

export interface RecordData {
  bloodGroup?: string | null;
  allergies?: string | null;
  conditions?: string[];
  medicines?: { name: string; dose?: string | null; since?: string | null }[];
  history?: string | null;
  fitness?: { status: 'FIT' | 'FIT_WITH_RESTRICTIONS' | 'UNFIT' | null; checkedOn?: string | null; note?: string | null } | null;
  vaccinations?: { name: string; date: string; dose?: string | null }[];
  emergencyNotes?: string | null;
}

export interface VisitData {
  complaint: string;
  findings?: string | null;
  treatment?: string | null;
  advice?: string | null;
}

async function log(userId: string, studentProfileId: string, action: string) {
  await db.medicalAccessLog.create({ data: { tenantId: getTenantIdOrThrow(), userId, studentProfileId, action } });
}

async function profile(id: string) {
  const p = await db.studentProfile.findFirst({ where: { id }, select: { id: true, userId: true, employeeCode: true, user: { select: { name: true } }, bed: { select: { label: true, room: { select: { number: true } } } } } });
  if (!p) throw new NotFoundError('Employee not found');
  return p;
}

/** Sealed to this tenant and employee: a value copied onto another row will not open. */
const ctx = (studentProfileId: string) => medicalContext(getTenantIdOrThrow(), studentProfileId);

/** One damaged value never takes the whole record down with it. */
function open<T>(sealed: string, studentProfileId: string, fallback: T): T {
  try {
    return openJson<T>(sealed, ctx(studentProfileId));
  } catch (err) {
    console.error('[medical] a sealed value would not open:', (err as Error).message); // eslint-disable-line no-console
    return fallback;
  }
}

const openVisit = (v: { id: string; studentProfileId: string; at: Date; sealed: string; fitForDuty: boolean | null; followUpOn: Date | null; createdById: string }) => ({ id: v.id, at: v.at, fitForDuty: v.fitForDuty, followUpOn: v.followUpOn, createdById: v.createdById, ...open<VisitData>(v.sealed, v.studentProfileId, { complaint: '(this entry could not be opened)' } as VisitData) });
const openAppointment = (a: { id: string; studentProfileId: string; at: Date; purpose: string; sealedNote: string | null; status: string }) => ({ id: a.id, at: a.at, purpose: a.purpose, status: a.status, note: a.sealedNote ? open<{ note: string | null }>(a.sealedNote, a.studentProfileId, { note: null }).note : null });

/** Who wrote each visit, by name. */
async function withAuthors<T extends { createdById: string }>(rows: T[]) {
  const ids = [...new Set(rows.map((r) => r.createdById))];
  const names = new Map((ids.length ? await db.user.findMany({ where: { id: { in: ids } }, select: { id: true, name: true } }) : []).map((u) => [u.id, u.name]));
  return rows.map((r) => ({ ...r, by: names.get(r.createdById) ?? null }));
}

/** The whole record for one employee: the record, visits, appointments, consent. Logged. */
async function fullRecord(studentProfileId: string) {
  const [rec, visits, appts] = await Promise.all([
    db.medicalRecord.findFirst({ where: { studentProfileId } }),
    db.ohcVisit.findMany({ where: { studentProfileId }, orderBy: { at: 'desc' }, take: 100 }),
    db.medicalAppointment.findMany({ where: { studentProfileId }, orderBy: { at: 'desc' }, take: 50 }),
  ]);
  return {
    consent: { given: !!rec?.consentAt && !rec.consentWithdrawnAt, at: rec?.consentAt ?? null, source: rec?.consentSource ?? null, withdrawnAt: rec?.consentWithdrawnAt ?? null },
    record: rec && rec.sealed ? { ...open<RecordData>(rec.sealed, studentProfileId, {} as RecordData), updatedAt: rec.updatedAt } : null,
    visits: await withAuthors(visits.map(openVisit)),
    appointments: appts.map(openAppointment),
  };
}

// ── The OHC ─────────────────────────────────────────────────────────────────

/** The OHC's list: employees, with whether there is a record, consent, the last visit and the next appointment. No clinical detail. */
/** With `pagination`, one page of the list and the total (Sprint L3); otherwise the first 500 (50 when searching) as before. */
export const PEOPLE_FILTERS = ['consent', 'none', 'booked'] as const;
export type PeopleFilter = (typeof PEOPLE_FILTERS)[number];

/**
 * The people a filter keeps (Sprint L4), as the apps' chips decided it on each
 * row: consent given and not withdrawn, or not; an appointment still to come.
 * Records and appointments hang off the profile by id, with no relation to join.
 */
async function filterWhere(filter: PeopleFilter | undefined, now: Date): Promise<Prisma.StudentProfileWhereInput> {
  if (!filter) return {};
  if (filter === 'booked') {
    const rows = await db.medicalAppointment.findMany({ where: { status: 'SCHEDULED', at: { gte: now } }, select: { studentProfileId: true }, distinct: ['studentProfileId'] });
    return { id: { in: rows.map((r) => r.studentProfileId) } };
  }
  const rows = await db.medicalRecord.findMany({ where: { consentAt: { not: null }, consentWithdrawnAt: null }, select: { studentProfileId: true } });
  const ids = rows.map((r) => r.studentProfileId);
  return filter === 'consent' ? { id: { in: ids } } : { id: { notIn: ids } };
}

export async function people(viewer: Viewer, q?: string, propertyId?: string, pagination?: Pagination | null, filter?: PeopleFilter) {
  assertOhc(viewer);
  const where: Prisma.StudentProfileWhereInput = {
    residencyStatus: { not: 'VACATED' },
    ...(propertyId ? { propertyId } : {}),
    ...(q ? { OR: [{ user: { name: { contains: q, mode: 'insensitive' } } }, { employeeCode: { contains: q, mode: 'insensitive' } }] } : {}),
    // Only a paged request filters: the unpaged list is what store builds read.
    ...(pagination ? await filterWhere(filter, new Date()) : {}),
  };
  const [rows, total] = await Promise.all([
    db.studentProfile.findMany({
      where,
      select: { id: true, employeeCode: true, user: { select: { name: true } }, bed: { select: { label: true, room: { select: { number: true } } } } },
      orderBy: pagination ? [{ user: { name: 'asc' } }, { id: 'asc' }] : { user: { name: 'asc' } },
      ...(pagination ? { skip: pagination.skip, take: pagination.limit } : { take: q ? 50 : 500 }),
    }),
    pagination ? db.studentProfile.count({ where }) : Promise.resolve(0),
  ]);
  const shown = await dressPeople(rows);
  return pagination ? paginated(shown, total, pagination) : shown;
}

async function dressPeople(rows: { id: string; employeeCode: string | null; user: { name: string }; bed: { label: string; room: { number: string } } | null }[]) {
  const ids = rows.map((r) => r.id);
  const [recs, lastVisits, next] = await Promise.all([
    db.medicalRecord.findMany({ where: { studentProfileId: { in: ids } }, select: { studentProfileId: true, consentAt: true, consentWithdrawnAt: true } }),
    db.ohcVisit.groupBy({ by: ['studentProfileId'], where: { studentProfileId: { in: ids } }, _max: { at: true } }),
    db.medicalAppointment.findMany({ where: { studentProfileId: { in: ids }, status: 'SCHEDULED', at: { gte: new Date() } }, orderBy: { at: 'asc' }, select: { studentProfileId: true, at: true, purpose: true } }),
  ]);
  const rec = new Map(recs.map((r) => [r.studentProfileId, r]));
  const visit = new Map(lastVisits.map((v) => [v.studentProfileId, v._max.at]));
  return rows.map((r) => {
    const x = rec.get(r.id);
    const n = next.find((a) => a.studentProfileId === r.id);
    return { studentProfileId: r.id, name: r.user.name, employeeCode: r.employeeCode, room: r.bed ? `Room ${r.bed.room.number} · Bed ${r.bed.label}` : null, hasRecord: !!x, consent: !!x?.consentAt && !x.consentWithdrawnAt, lastVisitAt: visit.get(r.id) ?? null, nextAppointment: n ? { at: n.at, purpose: n.purpose } : null };
  });
}

export async function getRecord(viewer: Viewer, studentProfileId: string) {
  assertOhc(viewer);
  const p = await profile(studentProfileId);
  await log(viewer.userId, studentProfileId, 'VIEW');
  return { employee: { studentProfileId: p.id, name: p.user.name, employeeCode: p.employeeCode, room: p.bed ? `Room ${p.bed.room.number} · Bed ${p.bed.label}` : null }, ...(await fullRecord(studentProfileId)) };
}

/** The record itself: only with consent in place. */
export async function saveRecord(viewer: Viewer, studentProfileId: string, data: RecordData) {
  assertOhc(viewer);
  await profile(studentProfileId);
  const rec = await db.medicalRecord.findFirst({ where: { studentProfileId } });
  if (!rec?.consentAt || rec.consentWithdrawnAt) throw new ConflictError('Record the employee’s consent first');
  await db.medicalRecord.update({ where: { id: rec.id }, data: { sealed: sealJson(data, ctx(studentProfileId)), updatedById: viewer.userId } });
  await log(viewer.userId, studentProfileId, 'EDIT');
  return getRecord(viewer, studentProfileId);
}

/** Consent on a signed form, recorded by the OHC. */
export async function recordPaperConsent(viewer: Viewer, studentProfileId: string) {
  assertOhc(viewer);
  await profile(studentProfileId);
  await giveConsent(studentProfileId, 'PAPER', viewer.userId);
  await log(viewer.userId, studentProfileId, 'CONSENT');
  return getRecord(viewer, studentProfileId);
}

async function giveConsent(studentProfileId: string, source: 'APP' | 'PAPER', byUserId: string) {
  const rec = await db.medicalRecord.findFirst({ where: { studentProfileId } });
  if (rec) return db.medicalRecord.update({ where: { id: rec.id }, data: { consentAt: new Date(), consentSource: source, consentWithdrawnAt: null } });
  return db.medicalRecord.create({ data: { tenantId: getTenantIdOrThrow(), studentProfileId, sealed: sealJson({}, ctx(studentProfileId)), consentAt: new Date(), consentSource: source, updatedById: byUserId } });
}

/** A visit can be written down without consent: care comes first. */
export async function addVisit(viewer: Viewer, studentProfileId: string, input: VisitData & { at?: Date; fitForDuty?: boolean | null; followUpOn?: Date | null }) {
  assertOhc(viewer);
  await profile(studentProfileId);
  const { at, fitForDuty, followUpOn, ...clinical } = input;
  const v = await db.ohcVisit.create({ data: { tenantId: getTenantIdOrThrow(), studentProfileId, at: at ?? new Date(), sealed: sealJson(clinical, ctx(studentProfileId)), fitForDuty: fitForDuty ?? null, followUpOn: followUpOn ?? null, createdById: viewer.userId } });
  await log(viewer.userId, studentProfileId, 'VISIT');
  return (await withAuthors([openVisit(v)]))[0];
}

export async function addAppointment(viewer: Viewer, studentProfileId: string, input: { at: Date; purpose: string; note?: string | null }) {
  assertOhc(viewer);
  await profile(studentProfileId);
  if (input.at.getTime() < Date.now() - 3_600_000) throw new BadRequestError('An appointment is in the future');
  const a = await db.medicalAppointment.create({ data: { tenantId: getTenantIdOrThrow(), studentProfileId, at: input.at, purpose: input.purpose, sealedNote: input.note ? sealJson({ note: input.note }, ctx(studentProfileId)) : null, createdById: viewer.userId } });
  await log(viewer.userId, studentProfileId, 'APPOINTMENT');
  return openAppointment(a);
}

export async function updateAppointment(viewer: Viewer, id: string, input: { status?: 'SCHEDULED' | 'DONE' | 'MISSED' | 'CANCELLED'; at?: Date }) {
  assertOhc(viewer);
  const a = await db.medicalAppointment.findFirst({ where: { id } });
  if (!a) throw new NotFoundError('Appointment not found');
  const u = await db.medicalAppointment.update({ where: { id }, data: { ...input, ...(input.at ? { remindedAt: null } : {}) } });
  await log(viewer.userId, a.studentProfileId, 'APPOINTMENT');
  return openAppointment(u);
}

/** The OHC's diary: appointments from today on (names and purposes only). Paged when asked (Sprint L3). */
export async function diary(viewer: Viewer, days = 14, pagination?: Pagination | null) {
  assertOhc(viewer);
  const where = { at: { gte: new Date(Date.now() - 12 * 3_600_000), lt: new Date(Date.now() + days * 86_400_000) } };
  const [rows, total] = await Promise.all([
    db.medicalAppointment.findMany({ where, orderBy: pagination ? [{ at: 'asc' }, { id: 'asc' }] : { at: 'asc' }, ...(pagination ? { skip: pagination.skip, take: pagination.limit } : { take: 500 }) }),
    pagination ? db.medicalAppointment.count({ where }) : Promise.resolve(0),
  ]);
  const shown = await dressDiary(rows);
  return pagination ? paginated(shown, total, pagination) : shown;
}

async function dressDiary(rows: { id: string; studentProfileId: string; at: Date; purpose: string; status: string }[]) {
  const who = new Map((await db.studentProfile.findMany({ where: { id: { in: rows.map((r) => r.studentProfileId) } }, select: { id: true, employeeCode: true, user: { select: { name: true } } } })).map((p) => [p.id, p]));
  return rows.map((r) => ({ id: r.id, studentProfileId: r.studentProfileId, name: who.get(r.studentProfileId)?.user.name ?? '—', employeeCode: who.get(r.studentProfileId)?.employeeCode ?? null, at: r.at, purpose: r.purpose, status: r.status }));
}

/** Who looked at or changed records: the OHC and the owner may read it (the owner sees names, not content). */
export async function accessLog(f: { studentProfileId?: string; days?: number }) {
  const rows = await db.medicalAccessLog.findMany({ where: { ...(f.studentProfileId ? { studentProfileId: f.studentProfileId } : {}), at: { gte: new Date(Date.now() - (f.days ?? 30) * 86_400_000) } }, orderBy: { at: 'desc' }, take: 1000 });
  return dressLog(rows);
}

/** The access log a page at a time (Sprint L3), newest first; the id breaks ties. */
export async function pageAccessLog(f: { studentProfileId?: string; days?: number }, pagination: Pagination) {
  const where = { ...(f.studentProfileId ? { studentProfileId: f.studentProfileId } : {}), at: { gte: new Date(Date.now() - (f.days ?? 30) * 86_400_000) } };
  const [rows, total] = await Promise.all([
    db.medicalAccessLog.findMany({ where, orderBy: [{ at: 'desc' }, { id: 'asc' }], skip: pagination.skip, take: pagination.limit }),
    db.medicalAccessLog.count({ where }),
  ]);
  return paginated(await dressLog(rows), total, pagination);
}

async function dressLog(rows: { id: string; at: Date; action: string; userId: string; studentProfileId: string }[]) {
  const users = new Map((await db.user.findMany({ where: { id: { in: [...new Set(rows.map((r) => r.userId))] } }, select: { id: true, name: true } })).map((u) => [u.id, u.name]));
  const emps = new Map((await db.studentProfile.findMany({ where: { id: { in: [...new Set(rows.map((r) => r.studentProfileId))] } }, select: { id: true, user: { select: { name: true } } } })).map((p) => [p.id, p.user.name]));
  return rows.map((r) => ({ id: r.id, at: r.at, action: r.action, by: users.get(r.userId) ?? '—', employee: emps.get(r.studentProfileId) ?? '—', studentProfileId: r.studentProfileId }));
}

/** For the owner: how much the OHC holds, without a single clinical word. */
export async function overview() {
  const [records, consented, visits30, upcoming] = await Promise.all([
    db.medicalRecord.count(),
    db.medicalRecord.count({ where: { consentAt: { not: null }, consentWithdrawnAt: null } }),
    db.ohcVisit.count({ where: { at: { gte: new Date(Date.now() - 30 * 86_400_000) } } }),
    db.medicalAppointment.count({ where: { status: 'SCHEDULED', at: { gte: new Date() } } }),
  ]);
  // Who can open records now, so the owner and the OHC see any change.
  return { records, consented, visits30, upcoming, ohcLogins: await ohcLogins() };
}

// ── The employee ────────────────────────────────────────────────────────────

async function myProfileId(userId: string) {
  const p = await db.studentProfile.findFirst({ where: { userId }, select: { id: true } });
  if (!p) throw new NotFoundError('No employee record for this account');
  return p.id;
}

/** Your own record, and who has looked at it. */
export async function mine(userId: string) {
  const id = await myProfileId(userId);
  const [full, log30] = await Promise.all([fullRecord(id), accessLog({ studentProfileId: id, days: 90 })]);
  return { profileId: id, ...full, accessLog: log30.map((l) => ({ at: l.at, action: l.action, by: l.by })) };
}

export async function consentMine(userId: string) {
  const id = await myProfileId(userId);
  await giveConsent(id, 'APP', userId);
  await log(userId, id, 'CONSENT');
  return mine(userId);
}

/** Withdrawn: the OHC can no longer change the record (visits still, for care). */
export async function withdrawMine(userId: string) {
  const id = await myProfileId(userId);
  const rec = await db.medicalRecord.findFirst({ where: { studentProfileId: id } });
  if (!rec?.consentAt || rec.consentWithdrawnAt) throw new ConflictError('There is no consent to withdraw');
  await db.medicalRecord.update({ where: { id: rec.id }, data: { consentWithdrawnAt: new Date() } });
  await log(userId, id, 'CONSENT');
  return mine(userId);
}

// ── Reminders ───────────────────────────────────────────────────────────────

/** Hourly: appointments in the next day remind the employee once — the time and a plain purpose only. */
export async function runAppointmentReminders(now = new Date()) {
  const due = await prismaUnscoped.medicalAppointment.findMany({ where: { status: 'SCHEDULED', remindedAt: null, at: { gt: now, lte: new Date(now.getTime() + 24 * 3_600_000) } }, take: 500 });
  for (const a of due) {
    if (!(await tenantHasFeature(a.tenantId, 'medical'))) continue;
    await prismaUnscoped.medicalAppointment.update({ where: { id: a.id }, data: { remindedAt: now } });
    const p = await prismaUnscoped.studentProfile.findUnique({ where: { id: a.studentProfileId }, select: { userId: true } });
    if (!p) continue;
    const when = a.at.toLocaleString('en-IN', { weekday: 'short', hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Kolkata' });
    await pushTo(a.tenantId, 'MEDICAL_APPOINTMENT', a.id, [p.userId], { title: `OHC appointment ${when}`, body: 'At the occupational health centre. Open the app for details.', data: { appointmentId: a.id } }).catch((err) => console.error('[push] appointment failed:', err)); // eslint-disable-line no-console
  }
}
