import { BedStatus } 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';

/**
 * The employee's company record (Sprint 1, TEPL): their TEPL ID, ID-card
 * number, department, contractor and usual shift — and a bed held for them
 * until they arrive, which their first punch on a terminal checks them into.
 * Only for tenants with employee records on.
 */

export const EMPLOYEE_KEYS = ['employeeCode', 'cardNumber', 'departmentId', 'contractor', 'defaultShiftId'] as const;
type EmployeeInput = Partial<Record<(typeof EMPLOYEE_KEYS)[number], string | null>>;

/** The validated employee fields to write, or nothing when none were sent. */
export async function employeeData(input: EmployeeInput, profileId?: string): Promise<Record<string, string | null>> {
  const sent = EMPLOYEE_KEYS.filter((k) => input[k] !== undefined);
  if (sent.length === 0) return {};
  if (!(await tenantHasFeature(getTenantIdOrThrow(), 'employeeRecords'))) throw new BadRequestError('Employee records are not available for this account');
  const out: Record<string, string | null> = {};
  for (const k of sent) out[k] = input[k] === '' ? null : (input[k] ?? null);

  const other = profileId ? { id: { not: profileId } } : {};
  if (out.employeeCode) {
    const clash = await db.studentProfile.findFirst({ where: { employeeCode: { equals: out.employeeCode, mode: 'insensitive' }, ...other }, select: { id: true } });
    if (clash) throw new ConflictError(`Employee ID ${out.employeeCode} is already used by someone else`);
  }
  if (out.cardNumber) {
    // A card number is also what a terminal may report, so it must not be someone else's terminal id either.
    const clash = await db.studentProfile.findFirst({ where: { OR: [{ cardNumber: out.cardNumber }, { biometricId: out.cardNumber }], ...other }, select: { id: true } });
    if (clash) throw new ConflictError(`Card ${out.cardNumber} is already used by someone else`);
  }
  if (out.departmentId && !(await db.department.findFirst({ where: { id: out.departmentId, isArchived: false }, select: { id: true } }))) throw new NotFoundError('Department not found');
  if (out.defaultShiftId && !(await db.shift.findFirst({ where: { id: out.defaultShiftId, isActive: true }, select: { id: true } }))) throw new NotFoundError('Shift not found');
  return out;
}

/**
 * Hold a vacant bed for an employee who has not arrived (or release it with
 * null). The bed shows as reserved; their first punch moves them in.
 */
export async function holdArrivalBed(profileId: string, bedId: string | null) {
  if (!(await tenantHasFeature(getTenantIdOrThrow(), 'employeeRecords'))) throw new BadRequestError('Not available for this account');
  return db.$transaction(async (tx) => {
    const profile = await tx.studentProfile.findFirst({ where: { id: profileId }, select: { id: true, bedId: true, arrivalBedId: true } });
    if (!profile) throw new NotFoundError('Employee not found');
    if (bedId && profile.bedId) throw new ConflictError('They already have a bed — move them instead');
    if (profile.arrivalBedId && profile.arrivalBedId !== bedId) {
      await tx.bed.updateMany({ where: { id: profile.arrivalBedId, status: BedStatus.RESERVED }, data: { status: BedStatus.VACANT } });
    }
    if (bedId && bedId !== profile.arrivalBedId) {
      const bed = await tx.bed.findFirst({ where: { id: bedId, archivedAt: null }, include: { room: { select: { floor: true, propertyId: true } } } });
      if (!bed) throw new NotFoundError('Bed not found');
      if (bed.room.floor == null) throw new ConflictError('Set a floor for this room before assigning its beds');
      if (bed.status !== BedStatus.VACANT) throw new ConflictError('Bed is not vacant');
      await tx.bed.update({ where: { id: bedId }, data: { status: BedStatus.RESERVED } });
      return tx.studentProfile.update({ where: { id: profileId }, data: { arrivalBedId: bedId, propertyId: bed.room.propertyId }, select: { id: true, arrivalBedId: true } });
    }
    return tx.studentProfile.update({ where: { id: profileId }, data: { arrivalBedId: bedId }, select: { id: true, arrivalBedId: true } });
  });
}

/**
 * The employee punched for the first time: move them into the bed held for
 * them, from the moment of the punch. Returns the bed's room and label, or
 * null when there was nothing to do (no bed held, or already in a bed).
 */
export async function checkInOnArrival(profileId: string, at: Date, assignBed: (profileId: string, bedId: string, movedInAt?: Date) => Promise<unknown>) {
  const profile = await db.studentProfile.findFirst({ where: { id: profileId }, select: { bedId: true, arrivalBedId: true, arrivalBed: { select: { label: true, room: { select: { number: true } } } } } });
  if (!profile?.arrivalBedId || profile.bedId) return null;
  const bedId = profile.arrivalBedId;
  // Release the hold, then move in through the normal path (floor, vacancy, billing rules).
  await db.$transaction([
    db.studentProfile.update({ where: { id: profileId }, data: { arrivalBedId: null } }),
    db.bed.updateMany({ where: { id: bedId, status: BedStatus.RESERVED }, data: { status: BedStatus.VACANT } }),
  ]);
  await assignBed(profileId, bedId, at);
  return { room: profile.arrivalBed?.room.number ?? '', bed: profile.arrivalBed?.label ?? '' };
}
