import { Prisma, Role } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { effectivePermissions } from '../../lib/permissions';

/**
 * Staff attendance (Sprint 3, TEPL): staff clock in and out from the app or
 * on an ESSL terminal; each has a duty shift per day from the same shift list
 * the roster uses; the day's board says who is on time, late, absent or off,
 * and the month's hours roll up for the report.
 */

export const STAFF_ROLES: Role[] = [Role.WARDEN, Role.MESS_ADMIN, Role.GUARD];
const IST_MS = 330 * 60_000;
const HOUR = 3_600_000;
const GRACE = 15 * 60_000;
export const istToday = (now = new Date()) => new Date(now.getTime() + IST_MS).toISOString().slice(0, 10);
const dayStart = (ymd: string) => Date.parse(`${ymd}T00:00:00.000Z`) - IST_MS;
const minutes = (hhmm: string) => {
  const [h, m] = hhmm.split(':').map(Number);
  return (h * 60 + m) * 60_000;
};

/**
 * A plant approver's login belongs to the plant, not the hostel: they do not
 * clock in here and are not on the hostel's duty roster. Anyone who also runs
 * something in the hostel (a MANAGE_ permission, or tasks) is staff all the same.
 */
export function isPlantOnly(role: Role, customPermissions?: string[] | null) {
  const perms = effectivePermissions(role, customPermissions);
  return perms.includes('APPROVE_PLANT_LEAVE') && !perms.some((p) => p.startsWith('MANAGE_') || p === 'WORK_TASKS');
}

/** A member of the hostel's staff, or not found. */
async function hostelStaffOrThrow(userId: string) {
  const u = await db.user.findFirst({ where: { id: userId, role: { in: STAFF_ROLES }, deactivatedAt: null }, select: { id: true, role: true, customRole: { select: { permissions: true } } } });
  if (!u || isPlantOnly(u.role, u.customRole?.permissions)) throw new NotFoundError('Staff member not found');
  return u;
}

async function lastPunch(userId: string) {
  return db.staffPunch.findFirst({ where: { userId }, orderBy: { at: 'desc' } });
}

/** Clock in or out from the app. Twice the same way in a row is refused. */
export async function clock(userId: string, role: Role, direction: 'IN' | 'OUT', note?: string | null) {
  if (!STAFF_ROLES.includes(role)) throw new BadRequestError('Only staff clock in');
  const me = await db.user.findFirst({ where: { id: userId }, select: { customRole: { select: { permissions: true } } } });
  if (isPlantOnly(role, me?.customRole?.permissions)) throw new BadRequestError('A plant login does not clock in at the hostel');
  const last = await lastPunch(userId);
  if (last && last.direction === direction && Date.now() - last.at.getTime() < 20 * HOUR) throw new ConflictError(direction === 'IN' ? 'You are already clocked in' : 'You are already clocked out');
  return db.staffPunch.create({ data: { tenantId: getTenantIdOrThrow(), userId, direction, at: new Date(), source: 'APP', note: note ?? null } });
}

export async function myDay(userId: string) {
  const today = istToday();
  const [punches, duty] = await Promise.all([
    db.staffPunch.findMany({ where: { userId, at: { gte: new Date(dayStart(today)) } }, orderBy: { at: 'asc' } }),
    dutyFor(userId, today),
  ]);
  return { day: today, punches, clockedIn: punches.at(-1)?.direction === 'IN', duty };
}

async function dutyFor(userId: string, day: string) {
  const d = await db.staffDuty.findFirst({ where: { userId, date: new Date(`${day}T00:00:00.000Z`) } });
  return d ? db.shift.findFirst({ where: { id: d.shiftId }, select: { id: true, code: true, name: true, startTime: true, endTime: true, isOff: true } }) : null;
}

/** Terminal punches from staff (matched by their terminal id), alternating in and out. Called from the punch ingest. */
export async function ingestStaffPunches(tenantId: string, deviceId: string, punches: { biometricId: string; at: Date }[]) {
  if (punches.length === 0 || !(await tenantHasFeature(tenantId, 'staffAttendance'))) return 0;
  const staff = await db.staffProfile.findMany({ where: { biometricId: { in: [...new Set(punches.map((p) => p.biometricId))] } }, select: { userId: true, biometricId: true } });
  const byId = new Map(staff.map((s) => [s.biometricId!, s.userId]));
  let made = 0;
  for (const p of punches.sort((a, b) => a.at.getTime() - b.at.getTime())) {
    const userId = byId.get(p.biometricId);
    if (!userId) continue;
    const last = await db.staffPunch.findFirst({ where: { userId, at: { lt: p.at } }, orderBy: { at: 'desc' } });
    const direction = last?.direction === 'IN' && p.at.getTime() - last.at.getTime() < 20 * HOUR ? 'OUT' : 'IN';
    try {
      await db.staffPunch.create({ data: { tenantId, userId, direction, at: p.at, source: 'DEVICE', deviceId } });
      made++;
    } catch (e) {
      if (!(e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002')) throw e;
    }
  }
  return made;
}

/** The office corrects a missed punch. */
export async function manualPunch(input: { userId: string; direction: 'IN' | 'OUT'; at: Date; note?: string | null }) {
  await hostelStaffOrThrow(input.userId);
  return db.staffPunch.create({ data: { tenantId: getTenantIdOrThrow(), ...input, source: 'MANUAL' } });
}

export async function setStaffBiometric(userId: string, biometricId: string | null) {
  await hostelStaffOrThrow(userId);
  if (biometricId) {
    const clash = (await db.staffProfile.findFirst({ where: { biometricId, userId: { not: userId } }, select: { id: true } })) || (await db.studentProfile.findFirst({ where: { OR: [{ biometricId }, { cardNumber: biometricId }] }, select: { id: true } }));
    if (clash) throw new ConflictError('That terminal id is already someone else’s');
  }
  // A login made under Staff has no profile row until a photo or salary is saved.
  return db.staffProfile.upsert({ where: { userId }, create: { tenantId: getTenantIdOrThrow(), userId, biometricId }, update: { biometricId }, select: { userId: true, biometricId: true } });
}

// ── Duties ──────────────────────────────────────────────────────────────────

/** The hostel's staff: plant approvers' logins left out. */
const staffList = async () =>
  (
    await db.user.findMany({
      where: { role: { in: STAFF_ROLES }, deactivatedAt: null },
      select: { id: true, name: true, role: true, customRole: { select: { name: true, permissions: true } }, staffProfile: { select: { biometricId: true, staffCode: true, plantName: true } } },
      orderBy: { name: 'asc' },
      take: 500,
    })
  ).filter((u) => !isPlantOnly(u.role, u.customRole?.permissions));

export async function duties(from: string, to: string) {
  const f = new Date(`${from}T00:00:00.000Z`);
  const t = new Date(`${to}T00:00:00.000Z`);
  if (t < f || (t.getTime() - f.getTime()) / 86_400_000 > 31) throw new BadRequestError('Up to a month at a time');
  const [staff, rows, shifts] = await Promise.all([staffList(), db.staffDuty.findMany({ where: { date: { gte: f, lte: t } } }), db.shift.findMany({ select: { id: true, code: true } })]);
  const code = new Map(shifts.map((s) => [s.id, s.code]));
  const days: string[] = [];
  for (let d = f.getTime(); d <= t.getTime(); d += 86_400_000) days.push(new Date(d).toISOString().slice(0, 10));
  return {
    days,
    staff: staff.map((u) => ({
      id: u.id,
      name: u.name,
      role: u.role,
      roleName: u.customRole?.name ?? null,
      biometricId: u.staffProfile?.biometricId ?? null,
      duties: Object.fromEntries(rows.filter((r) => r.userId === u.id).map((r) => [r.date.toISOString().slice(0, 10), { shiftId: r.shiftId, code: code.get(r.shiftId) ?? '?' }])),
    })),
  };
}

export async function setDuty(userId: string, date: string, shiftId: string | null) {
  const d = new Date(`${date}T00:00:00.000Z`);
  await hostelStaffOrThrow(userId);
  if (!shiftId) {
    await db.staffDuty.deleteMany({ where: { userId, date: d } });
    return null;
  }
  if (!(await db.shift.findFirst({ where: { id: shiftId, isActive: true }, select: { id: true } }))) throw new NotFoundError('Shift not found');
  return db.staffDuty.upsert({ where: { userId_date: { userId, date: d } }, create: { tenantId: getTenantIdOrThrow(), userId, date: d, shiftId }, update: { shiftId } });
}

// ── The board and the hours ─────────────────────────────────────────────────

export type StaffDayStatus = 'ON_TIME' | 'LATE' | 'ABSENT' | 'ON_DUTY' | 'OFF' | 'NO_DUTY' | 'UPCOMING' | 'PRESENT';

/** Worked time from in/out pairs; an in without an out counts up to `until`. */
function workedMs(punches: { direction: string; at: Date }[], until: number) {
  let total = 0;
  let inAt: number | null = null;
  for (const p of punches) {
    if (p.direction === 'IN') inAt ??= p.at.getTime();
    else if (inAt !== null) {
      total += p.at.getTime() - inAt;
      inAt = null;
    }
  }
  if (inAt !== null) total += Math.max(0, until - inAt);
  return total;
}

export async function dayBoard(day: string, now = new Date()) {
  const start = dayStart(day);
  const [staff, dutyRows, shifts, punches] = await Promise.all([
    staffList(),
    db.staffDuty.findMany({ where: { date: new Date(`${day}T00:00:00.000Z`) } }),
    db.shift.findMany(),
    db.staffPunch.findMany({ where: { at: { gte: new Date(start - 6 * HOUR), lt: new Date(start + 30 * HOUR) } }, orderBy: { at: 'asc' } }),
  ]);
  return boardOf(day, now, staff, dutyRows, new Map(shifts.map((s) => [s.id, s])), groupPunches(punches));
}

/**
 * The boards of a run of days (Sprint L4), each the same as `dayBoard(day, now)`,
 * from one read of the staff, shifts, duties and punches instead of four reads a
 * day one after another. Days in the order given.
 */
export async function dayBoards(days: string[], now = new Date()) {
  if (days.length === 0) return [];
  const sorted = [...days].sort();
  const first = dayStart(sorted[0]);
  const last = dayStart(sorted[sorted.length - 1]);
  const [staff, dutyRows, shifts, punches] = await Promise.all([
    staffList(),
    db.staffDuty.findMany({ where: { date: { in: [...new Set(days)].map((d) => new Date(`${d}T00:00:00.000Z`)) } } }),
    db.shift.findMany(),
    db.staffPunch.findMany({ where: { at: { gte: new Date(first - 6 * HOUR), lt: new Date(last + 30 * HOUR) } }, orderBy: { at: 'asc' } }),
  ]);
  const shiftOf = new Map(shifts.map((s) => [s.id, s]));
  const dutiesOn = new Map<string, typeof dutyRows>();
  for (const d of dutyRows) {
    const key = d.date.toISOString().slice(0, 10);
    const list = dutiesOn.get(key);
    if (list) list.push(d);
    else dutiesOn.set(key, [d]);
  }
  const byUser = groupPunches(punches);
  return days.map((day) => {
    // The same window `dayBoard` reads, so a day's board never sees punches it would not.
    const start = dayStart(day);
    const from = start - 6 * HOUR;
    const to = start + 30 * HOUR;
    const windowed = new Map([...byUser].map(([u, list]) => [u, list.filter((p) => p.at.getTime() >= from && p.at.getTime() < to)]));
    return boardOf(day, now, staff, dutiesOn.get(day) ?? [], shiftOf, windowed);
  });
}

type Punch = { userId: string; direction: string; at: Date };
type ShiftRow = { id: string; code: string; name: string; startTime: string | null; endTime: string | null; isOff: boolean };

/** Punches by person, each list in time order (the order they were read in). */
function groupPunches<P extends Punch>(punches: P[]) {
  const byUser = new Map<string, P[]>();
  for (const p of punches) {
    const list = byUser.get(p.userId);
    if (list) list.push(p);
    else byUser.set(p.userId, [p]);
  }
  return byUser;
}

/** One day's board from rows already read: every member of staff with their shift, punches, hours and status. */
function boardOf(day: string, now: Date, staff: Awaited<ReturnType<typeof staffList>>, dutyRows: { userId: string; shiftId: string }[], shiftOf: Map<string, ShiftRow>, punchesOf: Map<string, Punch[]>) {
  const start = dayStart(day);
  const dutyOf = new Map(dutyRows.map((d) => [d.userId, shiftOf.get(d.shiftId) ?? null]));
  const rows = staff.map((u) => {
    const shift = dutyOf.get(u.id) ?? null;
    let s = start;
    let e = start + 24 * HOUR;
    if (shift?.startTime && shift.endTime) {
      s = start + minutes(shift.startTime);
      e = start + minutes(shift.endTime);
      if (e <= s) e += 24 * HOUR;
    }
    // The day's punches: from a little before the shift to the end of it (or the calendar day without one).
    const mine = (punchesOf.get(u.id) ?? []).filter((p) => p.at.getTime() >= s - 3 * HOUR && p.at.getTime() < (shift?.startTime ? e + 3 * HOUR : start + 24 * HOUR));
    const firstIn = mine.find((p) => p.direction === 'IN')?.at ?? null;
    const lastOut = [...mine].reverse().find((p) => p.direction === 'OUT')?.at ?? null;
    const hours = Math.round((workedMs(mine, Math.min(now.getTime(), e)) / HOUR) * 10) / 10;
    let status: StaffDayStatus;
    if (shift?.isOff) status = firstIn ? 'PRESENT' : 'OFF';
    else if (!shift) status = firstIn ? 'PRESENT' : 'NO_DUTY';
    else if (!firstIn) status = now.getTime() < s + GRACE ? 'UPCOMING' : 'ABSENT';
    else if (mine.at(-1)?.direction === 'IN' && now.getTime() < e + 3 * HOUR) status = firstIn.getTime() > s + GRACE ? 'LATE' : 'ON_DUTY';
    else status = firstIn.getTime() > s + GRACE ? 'LATE' : 'ON_TIME';
    return {
      userId: u.id,
      name: u.name,
      role: u.role,
      roleName: u.customRole?.name ?? null,
      /** Their staff ID, or the terminal id until they have one. */
      staffCode: u.staffProfile?.staffCode ?? u.staffProfile?.biometricId ?? null,
      plantName: u.staffProfile?.plantName ?? null,
      shift: shift ? { code: shift.code, name: shift.name, startTime: shift.startTime, endTime: shift.endTime, isOff: shift.isOff } : null,
      firstIn,
      lastOut,
      hours,
      minutesLate: shift?.startTime && firstIn && firstIn.getTime() > s + GRACE ? Math.round((firstIn.getTime() - s) / 60_000) : null,
      status,
    };
  });
  const count = (x: StaffDayStatus) => rows.filter((r) => r.status === x).length;
  return { day, rows, summary: { staff: rows.length, onDuty: count('ON_DUTY'), onTime: count('ON_TIME'), late: count('LATE'), absent: count('ABSENT'), off: count('OFF'), noDuty: count('NO_DUTY') } };
}

/** A month (YYYY-MM) per member of staff: days present, hours, late days, absences. */
export async function monthHours(month: string, now = new Date()) {
  const [y, m] = month.split('-').map(Number);
  const days: string[] = [];
  const last = new Date(Date.UTC(y, m, 0)).getUTCDate();
  const today = istToday(now);
  for (let d = 1; d <= last; d++) {
    const day = `${month}-${String(d).padStart(2, '0')}`;
    if (day > today) break;
    days.push(day);
  }
  // One read for the month (Sprint L4); it was a `dayBoard` per day, one after another.
  const boards = await dayBoards(days, now);
  const staff = boards[0]?.rows ?? [];
  return staff.map((s) => {
    const rows = boards.map((b) => b.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: rows.filter((r) => r.firstIn).length,
      hours: Math.round(rows.reduce((n, r) => n + r.hours, 0) * 10) / 10,
      lateDays: rows.filter((r) => r.status === 'LATE').length,
      absences: rows.filter((r) => r.status === 'ABSENT').length,
    };
  });
}
