import { randomBytes } from 'node:crypto';
import { PassStatus, PunchDirection, PunchType, Role, StudentRequestStatus, StudentRequestType } 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 { passInclude, passTokenHash, publicPass, punch, qrFor } from '../gate/gate.service';
import { inBackground, pushTo, staffWith } from '../notifications/notifications.service';

/**
 * Quick outings (Sprint 4, TEPL): a pass to step out and be back the same
 * day — the market, a clinic — without a leave request. The employee asks in
 * the app and the warden approves or declines (4 Nov 2026); the gate or the
 * office can also give one to someone standing there. Once approved they show
 * the QR or swipe the terminal, and are back by the time they chose, curfew
 * at the latest.
 *
 * Also: the terminal's gate swipes move any pass along (out, then back), and
 * once a night, after curfew, the hostel hears who is still out with nothing
 * to cover it.
 */

const IST_MS = 330 * 60_000;
const HOUR = 3_600_000;
const MAX_HOURS = 16;
/** Allowed out, or on the way to it: what stops a second pass. */
const OPEN: PassStatus[] = [PassStatus.ACTIVE, PassStatus.OUT, PassStatus.OVERDUE, PassStatus.PENDING_GUARDIAN, PassStatus.PENDING_WARDEN];
/** What explains someone being out after curfew: an unanswered request does not. */
const COVERS_CURFEW: PassStatus[] = [PassStatus.ACTIVE, PassStatus.OUT, PassStatus.OVERDUE, PassStatus.PENDING_GUARDIAN];

const istYmd = (t: number) => new Date(t + IST_MS).toISOString().slice(0, 10);
const istClock = (d: Date) => d.toLocaleTimeString('en-IN', { hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Kolkata' });
/** The moment HH:MM falls on an India date. */
const istMoment = (ymd: string, hhmm: string) => {
  const [h, m] = hhmm.split(':').map(Number);
  return Date.parse(`${ymd}T00:00:00.000Z`) - IST_MS + (h * 60 + m) * 60_000;
};

async function profileFor(where: { userId: string } | { id: string }) {
  const p = await db.studentProfile.findFirst({
    where: { ...where, residencyStatus: { not: 'VACATED' } },
    select: { id: true, userId: true, propertyId: true, property: { select: { curfewTime: true } } },
  });
  if (!p) throw new NotFoundError('Employee not found');
  return p;
}

interface OutingInput {
  purpose: string;
  destination?: string | null;
  returnBy: Date;
  /** When they mean to go, later today. Now, if not given. */
  leaveAt?: Date | null;
}

/** Back by `returnBy`: later than now, the same day, and no later than curfew; and no other pass open. */
async function checkOuting(studentProfileId: string, input: OutingInput) {
  const p = await profileFor({ id: studentProfileId });
  const now = Date.now();
  const back = input.returnBy.getTime();
  if (back < now + 15 * 60_000) throw new BadRequestError('Give a return time at least 15 minutes from now');
  if (back > now + MAX_HOURS * HOUR) throw new BadRequestError(`A quick outing is for up to ${MAX_HOURS} hours; apply for leave for longer`);
  if (input.leaveAt) {
    if (input.leaveAt.getTime() >= back) throw new BadRequestError('The time going out must be before the time back');
    if (input.leaveAt.getTime() < now - 5 * 60_000) throw new BadRequestError('The time going out has passed');
  }
  const curfew = p.property?.curfewTime;
  if (curfew) {
    const tonight = istMoment(istYmd(now), curfew);
    if (now >= tonight) throw new BadRequestError(`It is past curfew (${curfew}); ask the warden`);
    if (back > tonight) throw new BadRequestError(`Be back by curfew (${curfew}), or apply for leave`);
  }
  // A pass never used, or a request never answered, and past its time does not count as open.
  const open = await db.gatePass.findFirst({ where: { studentProfileId, status: { in: OPEN }, NOT: { status: { in: [PassStatus.ACTIVE, PassStatus.PENDING_WARDEN] }, validTo: { lt: new Date(now) } } }, select: { id: true } });
  if (open) throw new ConflictError('There is already an open pass or request — use it, or close it first');
  return p;
}

/** A new outing pass row. Its QR exists only once it is approved, as the app asks for a fresh one then. */
async function createOuting(studentProfileId: string, input: OutingInput, approvedById: string, status: PassStatus, decided: { decidedById: string; decidedAt: Date } | null) {
  const token = randomBytes(24).toString('hex');
  const pass = await db.gatePass.create({
    data: {
      tenantId: getTenantIdOrThrow(),
      kind: 'OUTING',
      purpose: input.purpose.slice(0, 120),
      destination: input.destination?.slice(0, 120) ?? null,
      studentProfileId,
      validFrom: input.leaveAt && input.leaveAt.getTime() > Date.now() ? input.leaveAt : new Date(Date.now() - 60_000),
      validTo: input.returnBy,
      approvedById,
      ...decided,
      tokenHash: passTokenHash(token),
      status,
    },
    include: passInclude,
  });
  return { pass, token };
}

/** The employee asks; the warden answers. Nothing to show at the gate until then. */
export async function requestOuting(userId: string, input: OutingInput) {
  const p = await profileFor({ userId });
  await checkOuting(p.id, input);
  const { pass } = await createOuting(p.id, input, userId, PassStatus.PENDING_WARDEN, null);
  const tenantId = getTenantIdOrThrow();
  inBackground('push: outing requested', () => notifyOutingRequested(tenantId, pass.id));
  return { pass: publicPass(pass), qr: null };
}

async function pendingOuting(passId: string, propertyId?: string) {
  const pass = await db.gatePass.findFirst({ where: { id: passId, kind: 'OUTING', ...(propertyId ? { student: { propertyId } } : {}) } });
  if (!pass) throw new NotFoundError('Request not found');
  if (pass.status !== PassStatus.PENDING_WARDEN) throw new ConflictError('This request has already been answered');
  return pass;
}

/** Only one answer counts: if two wardens press at once, the second is told it is done. */
async function decide(passId: string, data: { status: PassStatus; approvedById?: string; decidedById: string; decidedAt: Date; decisionNote: string | null }) {
  const moved = await db.gatePass.updateMany({ where: { id: passId, status: PassStatus.PENDING_WARDEN }, data });
  if (!moved.count) throw new ConflictError('This request has already been answered');
  const tenantId = getTenantIdOrThrow();
  inBackground('push: outing decided', () => notifyOutingDecided(tenantId, passId));
  return publicPass(await db.gatePass.findFirstOrThrow({ where: { id: passId }, include: passInclude }));
}

export async function approveOuting(passId: string, actorId: string, propertyId?: string) {
  const pass = await pendingOuting(passId, propertyId);
  if (pass.validTo.getTime() < Date.now()) throw new ConflictError('The time to be back has passed; they will need to ask again');
  return decide(passId, { status: PassStatus.ACTIVE, approvedById: actorId, decidedById: actorId, decidedAt: new Date(), decisionNote: null });
}

export async function declineOuting(passId: string, reason: string, actorId: string, propertyId?: string) {
  await pendingOuting(passId, propertyId);
  return decide(passId, { status: PassStatus.DECLINED, decidedById: actorId, decidedAt: new Date(), decisionNote: reason.slice(0, 300) });
}

async function notifyOutingRequested(tenantId: string, passId: string) {
  const pass = await prismaUnscoped.gatePass.findFirst({ where: { id: passId, tenantId }, include: passInclude });
  if (!pass) return;
  const staff = await staffWith(tenantId, 'MANAGE_STUDENTS');
  await pushTo(tenantId, 'OUTING_REQUESTED', pass.id, staff, {
    title: `${pass.student.user.name} asks to go out`,
    body: `${pass.purpose ?? 'Outing'}, back by ${istClock(pass.validTo)}. Approve or decline under Outings.`,
    data: { passId: pass.id },
  });
}

async function notifyOutingDecided(tenantId: string, passId: string) {
  const pass = await prismaUnscoped.gatePass.findFirst({ where: { id: passId, tenantId }, include: passInclude });
  if (!pass) return;
  const approved = pass.status === PassStatus.ACTIVE;
  await pushTo(tenantId, 'OUTING_DECIDED', pass.id, [pass.student.user.id], {
    title: approved ? 'Your outing is approved' : 'Your outing was declined',
    body: approved ? `Show the QR under Quick outing at the gate. Be back by ${istClock(pass.validTo)}.` : (pass.decisionNote ?? 'See the warden.'),
    data: { passId: pass.id },
  });
}

/** Every open request, oldest first, for the warden. */
export async function pendingOutings(propertyId?: string) {
  const rows = await db.gatePass.findMany({
    where: { kind: 'OUTING', status: PassStatus.PENDING_WARDEN, validTo: { gte: new Date() }, ...(propertyId ? { student: { propertyId } } : {}) },
    include: passInclude,
    orderBy: { createdAt: 'asc' },
    take: 200,
  });
  return rows.map((r) => publicPass(r));
}

/** The gate gives one to an employee standing there, and lets them out at once. */
export async function giveOuting(input: { studentProfileId: string; purpose: string; destination?: string | null; returnBy: Date; outNow?: boolean }, actorId: string) {
  await checkOuting(input.studentProfileId, input);
  const { pass, token } = await createOuting(input.studentProfileId, input, actorId, PassStatus.ACTIVE, { decidedById: actorId, decidedAt: new Date() });
  const made = { pass: publicPass(pass), qr: qrFor(pass.id, token) };
  if (!input.outNow) return made;
  const r = await punch({ passId: made.pass.id, direction: PunchDirection.OUT }, actorId);
  return { pass: r.pass ?? made.pass, qr: made.qr };
}

/** The employee takes back a request, or calls it off before going out. */
export async function cancelMyOuting(userId: string, passId: string) {
  const p = await profileFor({ userId });
  const pass = await db.gatePass.findFirst({ where: { id: passId, studentProfileId: p.id, kind: 'OUTING' } });
  if (!pass) throw new NotFoundError('Pass not found');
  if (pass.status !== PassStatus.ACTIVE && pass.status !== PassStatus.PENDING_WARDEN) throw new ConflictError('Only an outing not yet started can be called off');
  return publicPass(await db.gatePass.update({ where: { id: pass.id }, data: { status: PassStatus.CANCELLED }, include: passInclude }));
}

/**
 * A day's outings (India day), for the office and the gate. Open requests come
 * apart from these, and only to those who can answer them; the gate has no
 * use for a request or a refusal.
 */
export async function listOutings(propertyId?: string, day = istYmd(Date.now()), office = false) {
  const start = new Date(Date.parse(`${day}T00:00:00.000Z`) - IST_MS);
  const end = new Date(start.getTime() + 24 * HOUR);
  const [rows, pending] = await Promise.all([
    db.gatePass.findMany({
      where: { kind: 'OUTING', status: { notIn: office ? [PassStatus.PENDING_WARDEN] : [PassStatus.PENDING_WARDEN, PassStatus.DECLINED] }, ...(propertyId ? { student: { propertyId } } : {}), OR: [{ createdAt: { gte: start, lt: end } }, { status: { in: [PassStatus.OUT, PassStatus.OVERDUE] } }] },
      include: passInclude,
      orderBy: { createdAt: 'desc' },
      take: 500,
    }),
    office ? pendingOutings(propertyId) : Promise.resolve([]),
  ]);
  const passes = rows.map((r) => publicPass(r));
  const count = (s: PassStatus) => passes.filter((x) => x.status === s).length;
  return { day, passes, pending, summary: { total: passes.length, out: count(PassStatus.OUT), overdue: count(PassStatus.OVERDUE), back: count(PassStatus.RETURNED), notStarted: count(PassStatus.ACTIVE), waiting: pending.length } };
}

/** Everyone who actually went out between two India days, for the report. */
export async function outingsBetween(from: string, to: string, propertyId?: string) {
  const start = new Date(Date.parse(`${from}T00:00:00.000Z`) - IST_MS);
  const end = new Date(Date.parse(`${to}T00:00:00.000Z`) - IST_MS + 24 * HOUR);
  const rows = await db.gatePass.findMany({
    where: { kind: 'OUTING', outAt: { gte: start, lt: end }, ...(propertyId ? { student: { propertyId } } : {}) },
    select: {
      studentProfileId: true,
      purpose: true,
      destination: true,
      outAt: true,
      inAt: true,
      validTo: true,
      decidedById: true,
      student: { select: { employeeCode: true, user: { select: { name: true } }, property: { select: { name: true } }, bed: { select: { room: { select: { number: true } } } } } },
    },
    orderBy: { outAt: 'desc' },
    take: 20000,
  });
  const deciders = await db.user.findMany({ where: { id: { in: [...new Set(rows.flatMap((r) => (r.decidedById ? [r.decidedById] : [])))] } }, select: { id: true, name: true } });
  const nameOf = new Map(deciders.map((u) => [u.id, u.name]));
  return rows.map((r) => ({
    studentProfileId: r.studentProfileId,
    name: r.student.user.name,
    employeeCode: r.student.employeeCode,
    block: r.student.property?.name ?? null,
    room: r.student.bed?.room.number ?? null,
    purpose: r.purpose,
    destination: r.destination,
    approvedBy: r.decidedById ? (nameOf.get(r.decidedById) ?? null) : null,
    outAt: r.outAt!,
    inAt: r.inAt,
    validTo: r.validTo,
  }));
}

// ── The terminal's swipes move passes ───────────────────────────────────────

/**
 * Gate swipes on the ESSL terminal, for employees: a swipe out starts the
 * pass that is valid now; a swipe in closes the one they are out on. Only
 * where quick outings are on, so a hostel's passes stay guard-scanned.
 */
export async function applyGateSwipes(tenantId: string, swipes: { studentProfileId: string; type: PunchType; at: Date }[]) {
  if (!swipes.length || !(await tenantHasFeature(tenantId, 'quickOutings'))) return 0;
  let moved = 0;
  for (const s of swipes.sort((a, b) => a.at.getTime() - b.at.getTime())) {
    if (s.type === PunchType.GATE_OUT) {
      const p = await db.gatePass.findFirst({ where: { studentProfileId: s.studentProfileId, status: PassStatus.ACTIVE, validFrom: { lte: s.at }, validTo: { gte: s.at } }, orderBy: { validFrom: 'desc' } });
      if (p) {
        await db.gatePass.update({ where: { id: p.id }, data: { status: PassStatus.OUT, outAt: s.at } });
        moved++;
      }
    } else if (s.type === PunchType.GATE_IN) {
      const p = await db.gatePass.findFirst({ where: { studentProfileId: s.studentProfileId, status: { in: [PassStatus.OUT, PassStatus.OVERDUE] }, outAt: { lte: s.at } }, orderBy: { outAt: 'desc' } });
      if (p) {
        await db.gatePass.update({ where: { id: p.id }, data: { status: PassStatus.RETURNED, inAt: s.at } });
        moved++;
      }
    }
  }
  return moved;
}

// ── Curfew ──────────────────────────────────────────────────────────────────

/** Where the gate last saw each employee, from guard taps and terminal swipes, up to `until`. */
async function lastGateEvents(ids: string[], since: Date, until: Date) {
  const [taps, swipes] = await Promise.all([
    db.gatePunch.findMany({ where: { studentProfileId: { in: ids }, at: { gte: since, lte: until } }, select: { studentProfileId: true, direction: true, at: true } }),
    db.biometricPunch.findMany({ where: { studentProfileId: { in: ids }, type: { in: [PunchType.GATE_IN, PunchType.GATE_OUT] }, punchedAt: { gte: since, lte: until } }, select: { studentProfileId: true, type: true, punchedAt: true } }),
  ]);
  const last = new Map<string, { dir: 'IN' | 'OUT'; at: Date }>();
  const see = (id: string | null, dir: 'IN' | 'OUT', at: Date) => {
    if (!id) return;
    const cur = last.get(id);
    if (!cur || at > cur.at) last.set(id, { dir, at });
  };
  for (const t of taps) see(t.studentProfileId, t.direction === PunchDirection.OUT ? 'OUT' : 'IN', t.at);
  for (const s of swipes) see(s.studentProfileId, s.type === PunchType.GATE_OUT ? 'OUT' : 'IN', s.punchedAt);
  return last;
}

/**
 * One block's night: employees whose last gate movement is out, with no pass
 * out, no leave today and no shift spanning curfew. Each is recorded once a
 * night; those who came back since are marked back.
 */
export async function checkCurfew(propertyId: string, curfew: string, now = new Date()) {
  const nowMs = now.getTime();
  // The night in question: today's curfew, or yesterday's in the small hours.
  let night = istYmd(nowMs);
  if (nowMs < istMoment(night, curfew)) night = istYmd(nowMs - 24 * HOUR);
  const curfewAt = istMoment(night, curfew);
  const dayDate = new Date(`${night}T00:00:00.000Z`);
  const people = await db.studentProfile.findMany({
    where: { propertyId, residencyStatus: { not: 'VACATED' }, bedId: { not: null } },
    select: { id: true, defaultShift: true, rosterEntries: { where: { date: dayDate }, include: { shift: true } } },
    take: 5000,
  });
  const ids = people.map((p) => p.id);
  const [events, passes, leaves, known] = await Promise.all([
    lastGateEvents(ids, new Date(curfewAt - 4 * 24 * HOUR), now),
    db.gatePass.findMany({ where: { studentProfileId: { in: ids }, status: { in: COVERS_CURFEW }, validFrom: { lte: now } }, select: { studentProfileId: true } }),
    db.studentRequest.findMany({ where: { studentProfileId: { in: ids }, type: StudentRequestType.LEAVE, status: StudentRequestStatus.APPROVED, fromDate: { lte: dayDate }, toDate: { gte: dayDate } }, select: { studentProfileId: true } }),
    db.curfewBreach.findMany({ where: { propertyId, date: dayDate }, select: { id: true, studentProfileId: true, backAt: true } }),
  ]);
  const covered = new Set([...passes.map((p) => p.studentProfileId), ...leaves.map((l) => l.studentProfileId)]);
  const onShift = (p: (typeof people)[number]) => {
    const s = p.rosterEntries[0]?.shift ?? p.defaultShift;
    if (!s || s.isOff || !s.startTime || !s.endTime) return false;
    const start = istMoment(night, s.startTime);
    let end = istMoment(night, s.endTime);
    if (end <= start) end += 24 * HOUR;
    // At work over curfew (or due to leave for a shift within the hour).
    return start - HOUR <= curfewAt && curfewAt < end;
  };
  const tenantId = getTenantIdOrThrow();
  const fresh: string[] = [];
  for (const p of people) {
    const e = events.get(p.id);
    const out = e?.dir === 'OUT';
    const k = known.find((x) => x.studentProfileId === p.id);
    if (k && !k.backAt && e?.dir === 'IN' && e.at.getTime() > curfewAt) await db.curfewBreach.update({ where: { id: k.id }, data: { backAt: e.at } });
    if (!out || k || covered.has(p.id) || onShift(p)) continue;
    const added = await db.curfewBreach.createMany({ data: [{ tenantId, propertyId, studentProfileId: p.id, date: dayDate, outSince: e!.at }], skipDuplicates: true });
    if (added.count) fresh.push(p.id);
  }
  return { night, fresh };
}

/** Hourly: every block past curfew tonight (within six hours of it) is checked; the office hears of new ones. */
export async function runCurfewPass(now = new Date()) {
  const tenants = await prismaUnscoped.tenant.findMany({ where: { status: 'ACTIVE', kind: 'ENTERPRISE' }, select: { id: true } });
  for (const t of tenants) {
    if (!(await tenantHasFeature(t.id, 'quickOutings'))) continue;
    const blocks = await prismaUnscoped.property.findMany({ where: { tenantId: t.id }, select: { id: true, name: true, curfewTime: true } });
    for (const b of blocks) {
      const nowMs = now.getTime();
      let night = istYmd(nowMs);
      if (nowMs < istMoment(night, b.curfewTime!)) night = istYmd(nowMs - 24 * HOUR);
      const since = nowMs - istMoment(night, b.curfewTime!);
      if (since < 30 * 60_000 || since > 6 * HOUR) continue;
      const r = await runWithTenantContext({ tenantId: t.id, userId: 'system', role: Role.HOSTEL_ADMIN }, () => checkCurfew(b.id, b.curfewTime!, now));
      if (r.fresh.length) inBackground('push: curfew', () => notifyCurfew(t.id, b.name, r.fresh.length));
    }
  }
}

async function notifyCurfew(tenantId: string, block: string, count: number) {
  const staff = await staffWith(tenantId, 'MANAGE_STUDENTS');
  await pushTo(tenantId, 'CURFEW_BREACH', `${block}:${istYmd(Date.now())}`, staff, {
    title: `${count} out after curfew · ${block}`,
    body: `${count} employee${count === 1 ? ' is' : 's are'} still out after curfew with no pass, leave or shift to cover it.`,
    data: { block },
  });
}

export async function curfewBreaches(propertyId: string | undefined, date: string) {
  const rows = await db.curfewBreach.findMany({
    where: { date: new Date(`${date}T00:00:00.000Z`), ...(propertyId ? { propertyId } : {}) },
    orderBy: { outSince: 'asc' },
  });
  const people = await db.studentProfile.findMany({
    where: { id: { in: rows.map((r) => r.studentProfileId) } },
    select: { id: true, employeeCode: true, user: { select: { name: true, phone: true } }, bed: { select: { label: true, room: { select: { number: true } } } }, property: { select: { name: true } } },
  });
  const who = new Map(people.map((p) => [p.id, p]));
  return rows.map((r) => {
    const p = who.get(r.studentProfileId);
    return { ...r, name: p?.user.name ?? '—', phone: p?.user.phone ?? null, employeeCode: p?.employeeCode ?? null, room: p?.bed ? `Room ${p.bed.room.number} · Bed ${p.bed.label}` : null, block: p?.property?.name ?? null };
  });
}
