import { Prisma } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, NotFoundError } from '../../lib/errors';

/**
 * Shifts and the daily roster (Sprint 1, TEPL). The plant sends who works
 * which shift each day — as a file until TEPL's roster API is connected —
 * and the adherence report (roster-adherence.ts) checks it against the gate.
 * An employee with no roster row for a day falls back to their usual shift.
 */

const DAY_MS = 86_400_000;
const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;

/** Our default shift list until TEPL sends theirs (docs/enterprise/defaults.md). */
const DEFAULT_SHIFTS = [
  { code: 'A', name: 'First shift', startTime: '06:00', endTime: '14:00', isOff: false },
  { code: 'B', name: 'Second shift', startTime: '14:00', endTime: '22:00', isOff: false },
  { code: 'C', name: 'Night shift', startTime: '22:00', endTime: '06:00', isOff: false },
  { code: 'G', name: 'General', startTime: '09:00', endTime: '18:00', isOff: false },
  { code: 'WO', name: 'Weekly off', startTime: null, endTime: null, isOff: true },
];

export async function listShifts(includeInactive = false) {
  if ((await db.shift.count()) === 0) {
    const tenantId = getTenantIdOrThrow();
    await db.shift.createMany({ data: DEFAULT_SHIFTS.map((s, i) => ({ ...s, tenantId, sortOrder: i })), skipDuplicates: true });
  }
  return db.shift.findMany({ where: includeInactive ? {} : { isActive: true }, orderBy: [{ isActive: 'desc' }, { sortOrder: 'asc' }] });
}

export interface ShiftInput {
  code: string;
  name: string;
  startTime: string | null;
  endTime: string | null;
  isOff: boolean;
  isActive: boolean;
}

/** Save the whole list. A shift left out is switched off, not deleted: the roster's history keeps it. */
export async function saveShifts(items: ShiftInput[]) {
  const tenantId = getTenantIdOrThrow();
  const codes = items.map((s) => s.code.toUpperCase());
  if (new Set(codes).size !== codes.length) throw new BadRequestError('Two shifts share a code');
  for (const s of items) {
    if (!s.isOff && (!s.startTime || !s.endTime || !TIME.test(s.startTime) || !TIME.test(s.endTime))) throw new BadRequestError(`Shift ${s.code} needs a start and an end, as HH:MM`);
  }
  await listShifts();
  await db.$transaction([
    db.shift.updateMany({ where: { code: { notIn: codes } }, data: { isActive: false } }),
    ...items.map((s, i) => {
      const data = { name: s.name, startTime: s.isOff ? null : s.startTime, endTime: s.isOff ? null : s.endTime, isOff: s.isOff, isActive: s.isActive, sortOrder: i };
      return db.shift.upsert({ where: { tenantId_code: { tenantId, code: s.code.toUpperCase() } }, create: { ...data, tenantId, code: s.code.toUpperCase() }, update: data });
    }),
  ]);
  return listShifts(true);
}

// ── Import ──────────────────────────────────────────────────────────────────

/** A day from a sheet: 2026-11-10, 10-11-2026, 10/11/2026, or Excel's day number. */
export function parseDay(raw: string): Date | null {
  const v = raw.trim();
  let y: number, m: number, d: number;
  let match = /^(\d{4})-(\d{1,2})-(\d{1,2})/.exec(v);
  if (match) [y, m, d] = [Number(match[1]), Number(match[2]), Number(match[3])];
  else if ((match = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/.exec(v))) [d, m, y] = [Number(match[1]), Number(match[2]), Number(match[3])];
  else if (/^\d{5}(\.\d+)?$/.test(v)) {
    // Excel counts days from 30 Dec 1899.
    const t = Date.UTC(1899, 11, 30) + Math.floor(Number(v)) * DAY_MS;
    return new Date(t);
  } else return null;
  const date = new Date(Date.UTC(y, m - 1, d));
  return date.getUTCFullYear() === y && date.getUTCMonth() === m - 1 && date.getUTCDate() === d ? date : null;
}

export interface RosterRow {
  employeeCode: string;
  date: string;
  shift: string;
}

/**
 * Load roster rows. Each employee-day in the sheet replaces what was there;
 * days the sheet does not mention are left alone. Every row is checked
 * first, and the good ones are saved even when some fail, so the report can
 * be fixed and sent again.
 */
export async function importRoster(rows: RosterRow[]) {
  const tenantId = getTenantIdOrThrow();
  const shifts = await listShifts();
  const shiftByCode = new Map(shifts.map((s) => [s.code.toLowerCase(), s]));
  const people = await db.studentProfile.findMany({ where: { employeeCode: { not: null } }, select: { id: true, employeeCode: true } });
  const byCode = new Map(people.map((p) => [p.employeeCode!.toLowerCase(), p.id]));

  const errors: { row: number; message: string }[] = [];
  const good = new Map<string, Prisma.RosterEntryCreateManyInput>();
  rows.forEach((r, i) => {
    const row = i + 2; // the sheet's own line, under its header
    const profileId = byCode.get(r.employeeCode.trim().toLowerCase());
    const date = parseDay(r.date);
    const shift = shiftByCode.get(r.shift.trim().toLowerCase());
    if (!profileId) return errors.push({ row, message: `No employee with ID ${r.employeeCode}` });
    if (!date) return errors.push({ row, message: `“${r.date}” is not a date` });
    if (!shift) return errors.push({ row, message: `Shift ${r.shift} is not in the shift list` });
    // A later row for the same employee-day wins, as it would on paper.
    good.set(`${profileId}:${date.toISOString()}`, { tenantId, studentProfileId: profileId, date, shiftId: shift.id, source: 'IMPORT' });
  });

  const entries = [...good.values()];
  for (let i = 0; i < entries.length; i += 1000) {
    const chunk = entries.slice(i, i + 1000);
    await db.$transaction([
      db.rosterEntry.deleteMany({ where: { OR: chunk.map((e) => ({ studentProfileId: e.studentProfileId, date: e.date })) } }),
      db.rosterEntry.createMany({ data: chunk }),
    ]);
  }
  const days = [...new Set(entries.map((e) => (e.date as Date).toISOString().slice(0, 10)))].sort();
  return { saved: entries.length, failed: errors.length, from: days[0] ?? null, to: days[days.length - 1] ?? null, errors: errors.slice(0, 200) };
}

// ── The grid ────────────────────────────────────────────────────────────────

const day = (s: string) => new Date(`${s}T00:00:00.000Z`);

/** Employees down, days across: the shift for each, from the roster or their usual one. */
export async function rosterGrid(from: string, to: string, filters: { propertyId?: string; departmentId?: string; q?: string; profileId?: string }) {
  const f = day(from);
  const t = day(to);
  if (t < f) throw new BadRequestError('The range ends before it starts');
  if ((t.getTime() - f.getTime()) / DAY_MS > 31) throw new BadRequestError('Up to a month at a time');
  const people = await db.studentProfile.findMany({
    where: {
      residencyStatus: { not: 'VACATED' },
      ...(filters.profileId ? { id: filters.profileId } : {}),
      ...(filters.propertyId ? { propertyId: filters.propertyId } : {}),
      ...(filters.departmentId ? { departmentId: filters.departmentId } : {}),
      ...(filters.q ? { OR: [{ user: { name: { contains: filters.q, mode: 'insensitive' } } }, { employeeCode: { contains: filters.q, mode: 'insensitive' } }] } : {}),
    },
    select: {
      id: true,
      employeeCode: true,
      user: { select: { name: true } },
      department: { select: { name: true } },
      // Names and times ride along, so an employee's own view needs no shift list.
      defaultShift: { select: { id: true, code: true, name: true, startTime: true, endTime: true, isOff: true } },
      rosterEntries: { where: { date: { gte: f, lte: t } }, select: { date: true, source: true, shift: { select: { id: true, code: true, name: true, startTime: true, endTime: true, isOff: true } } } },
    },
    orderBy: { user: { name: 'asc' } },
    take: 1000,
  });
  const days: string[] = [];
  for (let d = f.getTime(); d <= t.getTime(); d += DAY_MS) days.push(new Date(d).toISOString().slice(0, 10));
  return {
    days,
    employees: people.map((p) => ({
      id: p.id,
      name: p.user.name,
      employeeCode: p.employeeCode,
      department: p.department?.name ?? null,
      defaultShift: p.defaultShift,
      shifts: Object.fromEntries(p.rosterEntries.map((e) => [e.date.toISOString().slice(0, 10), { ...e.shift, source: e.source }])),
    })),
  };
}

/** Set (or clear, with null) one employee's shift for one day. */
export async function setEntry(profileId: string, date: string, shiftId: string | null) {
  const d = day(date);
  if (!(await db.studentProfile.findFirst({ where: { id: profileId }, select: { id: true } }))) throw new NotFoundError('Employee not found');
  if (!shiftId) {
    await db.rosterEntry.deleteMany({ where: { studentProfileId: profileId, 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.rosterEntry.upsert({
    where: { studentProfileId_date: { studentProfileId: profileId, date: d } },
    create: { tenantId: getTenantIdOrThrow(), studentProfileId: profileId, date: d, shiftId, source: 'MANUAL' },
    update: { shiftId, source: 'MANUAL' },
    include: { shift: { select: { id: true, code: true } } },
  });
}

/** An employee's own shifts for the days ahead. */
export async function myRoster(userId: string, from: string, to: string) {
  const p = await db.studentProfile.findFirst({ where: { userId }, select: { id: true } });
  if (!p) throw new NotFoundError('No employee record for this account');
  const grid = await rosterGrid(from, to, { profileId: p.id });
  return { days: grid.days, me: grid.employees[0] ?? null };
}
