import { PunchType, StudentRequestStatus, StudentRequestType } from '@prisma/client';
import { db } from '../../lib/prisma';
import { BadRequestError } from '../../lib/errors';

/**
 * Shift adherence (Sprint 1, TEPL): for one day, each rostered employee's
 * shift against what the gate saw — terminal punches and guard scans
 * together. Times are India time.
 *
 * - On shift: out of the hostel by the shift's start (30 minutes' grace) is
 *   ON_TIME; out later is LATE; never out is NO_SWIPE_OUT.
 * - On approved leave: ON_LEAVE, or ON_LEAVE_IN_HOSTEL when the gate shows
 *   them in during the day.
 * - Weekly off: WEEKLY_OFF, or OFF_OUT_AFTER_CURFEW when out past curfew.
 * - UPCOMING before the shift is due; NO_DATA for someone the gate has never
 *   seen (no terminal enrolment, no scans).
 */

export type AdherenceStatus = 'ON_TIME' | 'LATE' | 'NO_SWIPE_OUT' | 'ON_LEAVE' | 'ON_LEAVE_IN_HOSTEL' | 'WEEKLY_OFF' | 'OFF_OUT_AFTER_CURFEW' | 'UPCOMING' | 'NO_DATA';

/** The ones somebody should look at. */
export const FLAGGED: AdherenceStatus[] = ['LATE', 'NO_SWIPE_OUT', 'ON_LEAVE_IN_HOSTEL', 'OFF_OUT_AFTER_CURFEW'];

const IST_MS = 330 * 60_000;
const HOUR = 3_600_000;
const GRACE = 30 * 60_000;
const LEAD = 3 * HOUR;

const minutesOf = (hhmm: string) => {
  const [h, m] = hhmm.split(':').map(Number);
  return (h * 60 + m) * 60_000;
};

type Event = { at: Date; dir: 'IN' | 'OUT' };

function stateAt(events: Event[], t: number): 'IN' | 'OUT' | 'UNKNOWN' {
  let s: 'IN' | 'OUT' | 'UNKNOWN' = 'UNKNOWN';
  for (const e of events) {
    if (e.at.getTime() > t) break;
    s = e.dir;
  }
  return s;
}

export async function adherence(date: string, filters: { propertyId?: string; departmentId?: string } = {}, now = new Date()) {
  if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new BadRequestError('date must be YYYY-MM-DD');
  const dayUtc = new Date(`${date}T00:00:00.000Z`);
  const start = dayUtc.getTime() - IST_MS; // midnight in India

  const people = await db.studentProfile.findMany({
    where: {
      residencyStatus: { not: 'VACATED' },
      ...(filters.propertyId ? { propertyId: filters.propertyId } : {}),
      ...(filters.departmentId ? { departmentId: filters.departmentId } : {}),
      OR: [{ rosterEntries: { some: { date: dayUtc } } }, { defaultShiftId: { not: null } }],
    },
    select: {
      id: true,
      employeeCode: true,
      user: { select: { name: true } },
      department: { select: { name: true } },
      bed: { select: { label: true, room: { select: { number: true } } } },
      property: { select: { name: true, curfewTime: true } },
      defaultShift: true,
      rosterEntries: { where: { date: dayUtc }, include: { shift: true } },
    },
    orderBy: { user: { name: 'asc' } },
    take: 5000,
  });
  const ids = people.map((p) => p.id);
  const windowFrom = new Date(start - 12 * HOUR);
  const windowTo = new Date(start + 36 * HOUR);
  const [punches, scans, leaves] = await Promise.all([
    db.biometricPunch.findMany({ where: { studentProfileId: { in: ids }, type: { in: [PunchType.GATE_IN, PunchType.GATE_OUT] }, punchedAt: { gte: windowFrom, lt: windowTo } }, select: { studentProfileId: true, type: true, punchedAt: true } }),
    db.gatePunch.findMany({ where: { studentProfileId: { in: ids }, at: { gte: windowFrom, lt: windowTo } }, select: { studentProfileId: true, direction: true, at: true } }),
    db.studentRequest.findMany({ where: { studentProfileId: { in: ids }, type: StudentRequestType.LEAVE, status: StudentRequestStatus.APPROVED, fromDate: { lte: dayUtc }, toDate: { gte: dayUtc } }, select: { studentProfileId: true, leaveType: { select: { code: true } } } }),
  ]);
  // Ever seen at the gate at all? Someone never enrolled cannot be judged.
  const seen = new Set(
    (await db.biometricPunch.groupBy({ by: ['studentProfileId'], where: { studentProfileId: { in: ids }, type: { in: [PunchType.GATE_IN, PunchType.GATE_OUT] } } })).map((r) => r.studentProfileId),
  );
  for (const s of await db.gatePunch.groupBy({ by: ['studentProfileId'], where: { studentProfileId: { in: ids } } })) seen.add(s.studentProfileId);

  const events = new Map<string, Event[]>();
  const push = (id: string | null, e: Event) => {
    if (!id) return;
    const list = events.get(id) ?? [];
    list.push(e);
    events.set(id, list);
  };
  for (const p of punches) push(p.studentProfileId, { at: p.punchedAt, dir: p.type === PunchType.GATE_OUT ? 'OUT' : 'IN' });
  for (const s of scans) push(s.studentProfileId, { at: s.at, dir: s.direction === 'OUT' ? 'OUT' : 'IN' });
  for (const list of events.values()) list.sort((a, b) => a.at.getTime() - b.at.getTime());
  const onLeave = new Map(leaves.map((l) => [l.studentProfileId, l.leaveType?.code ?? 'Leave']));

  const rows = people.map((p) => {
    const entry = p.rosterEntries[0];
    const shift = entry?.shift ?? p.defaultShift!;
    const ev = events.get(p.id) ?? [];
    const base = {
      studentProfileId: p.id,
      name: p.user.name,
      employeeCode: p.employeeCode,
      department: p.department?.name ?? null,
      property: p.property?.name ?? null,
      room: p.bed ? `${p.bed.room.number} / ${p.bed.label}` : null,
      shift: { code: shift.code, name: shift.name, startTime: shift.startTime, endTime: shift.endTime, isOff: shift.isOff },
      fromRoster: !!entry,
      outAt: null as Date | null,
      inAt: null as Date | null,
      minutesLate: null as number | null,
      leave: onLeave.get(p.id) ?? null,
    };
    const result = (status: AdherenceStatus, extra: Partial<typeof base> = {}) => ({ ...base, ...extra, status, flagged: FLAGGED.includes(status) });

    if (onLeave.has(p.id)) {
      const inDuringDay = ev.some((e) => e.dir === 'IN' && e.at.getTime() >= start + 8 * HOUR && e.at.getTime() <= start + 20 * HOUR) || stateAt(ev, start + 12 * HOUR) === 'IN';
      return result(inDuringDay && seen.has(p.id) ? 'ON_LEAVE_IN_HOSTEL' : 'ON_LEAVE');
    }
    if (shift.isOff || !shift.startTime || !shift.endTime) {
      const curfew = start + minutesOf(p.property?.curfewTime ?? '22:00');
      if (now.getTime() > curfew && stateAt(ev, curfew) === 'OUT') return result('OFF_OUT_AFTER_CURFEW');
      return result('WEEKLY_OFF');
    }
    const s = start + minutesOf(shift.startTime);
    let e = start + minutesOf(shift.endTime);
    if (e <= s) e += 24 * HOUR;
    if (now.getTime() < s + GRACE) return result('UPCOMING');
    if (!seen.has(p.id)) return result('NO_DATA');
    const out = ev.find((x) => x.dir === 'OUT' && x.at.getTime() >= s - LEAD && x.at.getTime() < e);
    const back = out ? (ev.find((x) => x.dir === 'IN' && x.at.getTime() > out.at.getTime()) ?? null) : null;
    if (out) {
      const late = out.at.getTime() - s;
      return late <= GRACE ? result('ON_TIME', { outAt: out.at, inAt: back?.at ?? null }) : result('LATE', { outAt: out.at, inAt: back?.at ?? null, minutesLate: Math.round(late / 60_000) });
    }
    // Left earlier than three hours before and never came back: out for the shift all the same.
    if (stateAt(ev, s + GRACE) === 'OUT') return result('ON_TIME');
    return result('NO_SWIPE_OUT');
  });

  const count = (st: AdherenceStatus) => rows.filter((r) => r.status === st).length;
  return {
    date,
    rows,
    summary: {
      rostered: rows.length,
      onTime: count('ON_TIME'),
      late: count('LATE'),
      noSwipeOut: count('NO_SWIPE_OUT'),
      onLeave: count('ON_LEAVE'),
      onLeaveInHostel: count('ON_LEAVE_IN_HOSTEL'),
      weeklyOff: count('WEEKLY_OFF'),
      offOutAfterCurfew: count('OFF_OUT_AFTER_CURFEW'),
      upcoming: count('UPCOMING'),
      noData: count('NO_DATA'),
      flagged: rows.filter((r) => r.flagged).length,
    },
  };
}
