import { Request, Response } from 'express';
import { z, ZodError } from 'zod';
import { BedStatus, RateBasis, TenantKind } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { AppError, BadRequestError } from '../../lib/errors';
import { addBed, createRoom, floorFromRoomNumber, setBedRent } from '../rooms/rooms.service';
import { assertNoDuplicateStudent, onboardStudent } from './students.service';
import { nextBedLabel } from '../../lib/bed-labels';
import { dormitoryImportStudentSchema, employeeImportStudentSchema, hostelOnboardStudentSchema } from './students.schemas';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { departmentByName } from '../departments/departments.service';

/**
 * Import rooms and students from the owner's sheet (Sprint L5): the answer
 * to "we already use Excel". The app reads the .xlsx or .csv in the browser
 * and sends rows; each row is a person, optionally in a room and bed.
 *
 * When a room is supplied, missing rooms are made (with the hostel's billing
 * basis); a named bed is used or made; with no bed, the room's first free bed
 * is taken (or one is added). With no room, no accommodation is assigned.
 * Rent, if given, is set on the selected bed. Each row stands alone: one bad
 * row is reported and the rest carry on. The usual plan limits apply, so a
 * row past the plan's beds is refused with the reason.
 */

export const importRowsSchema = z.object({
  rows: z
    .array(
      z.object({
        // Checked row by row below, so one bad row does not refuse the sheet.
        room: z.string().trim().max(40).optional().nullable(),
        bed: z.string().trim().max(20).optional().nullable(),
        name: z.string().trim().max(200),
        email: z.string().trim().max(320).optional().nullable(),
        password: z.string().max(200).optional().nullable(),
        phone: z.string().trim().max(20).optional().nullable(),
        address: z.string().trim().max(300).optional().nullable(),
        state: z.string().trim().max(80).optional().nullable(),
        city: z.string().trim().max(80).optional().nullable(),
        postalCode: z.string().trim().max(12).optional().nullable(),
        rent: z.number().int().min(0).max(1_000_000).optional().nullable(),
        movedInAt: z.string().trim().max(30).optional().nullable(),
        joinedOn: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Use a date like 2026-04-01').optional().nullable(),
        guardianName: z.string().trim().max(120).optional().nullable(),
        guardianPhone: z.string().trim().max(20).optional().nullable(),
        parentName: z.string().trim().max(120).optional().nullable(),
        parentPhone: z.string().trim().max(20).optional().nullable(),
        depositAmount: z.number().int().min(0).max(10_000_000).optional().nullable(),
        depositPaid: z.number().int().min(0).max(10_000_000).optional().nullable(),
        depositPaidAt: z.string().trim().max(30).optional().nullable(),
        depositMethod: z.string().trim().max(20).optional().nullable(),
        depositReference: z.string().trim().max(80).optional().nullable(),
        kycIdType: z.string().trim().max(30).optional().nullable(),
        kycIdNumber: z.string().trim().max(30).optional().nullable(),
        kycStatus: z.string().trim().max(20).optional().nullable(),
        idProofUrl: z.string().trim().max(500).optional().nullable(),
        photoUrl: z.string().trim().max(500).optional().nullable(),
        // Sprint 1 (TEPL): the floor of a room the sheet creates, and the employee record.
        floor: z.number().int().min(0).max(200).optional().nullable(),
        employeeCode: z.string().trim().max(40).optional().nullable(),
        cardNumber: z.string().trim().max(40).optional().nullable(),
        department: z.string().trim().max(80).optional().nullable(),
        contractor: z.string().trim().max(120).optional().nullable(),
        shift: z.string().trim().max(10).optional().nullable(),
      }),
    )
    .min(1, 'The sheet has no rows')
    .max(500, 'Import at most 500 rows at a time'),
});

type Row = z.infer<typeof importRowsSchema>['rows'][number];
const phoneOk = (p: string | null | undefined) => !p || p.replace(/\D/g, '').length >= 7;

export async function importStudents(rows: Row[], actorId: string, propertyIdIn?: string) {
  const tenantId = getTenantIdOrThrow();
  const property = propertyIdIn ? await db.property.findFirst({ where: { id: propertyIdIn } }) : await db.property.findFirst({ orderBy: { createdAt: 'asc' } });
  if (!property) throw new BadRequestError('Add a property first.');
  const tenant = await prismaUnscoped.tenant.findUnique({ where: { id: tenantId }, select: { kind: true } });
  const daily = tenant?.kind === TenantKind.DORMITORY;
  const results: { row: number; status: 'created' | 'error'; message?: string; room?: string; bed?: string; name: string }[] = [];
  let roomsMade = 0;
  let bedsMade = 0;
  const employees = await tenantHasFeature(tenantId, 'employeeRecords');

  for (const [i, r] of rows.entries()) {
    const row = i + 2; // the sheet's own line number, under its header
    try {
      if (r.room && r.room.length > 20) throw new BadRequestError('Room must be at most 20 characters');
      if (r.bed && !r.room) throw new BadRequestError('A bed can only be imported with a room');
      if (r.rent != null && !r.room) throw new BadRequestError('Rent can only be imported with a room');
      if (r.name.length < 2) throw new BadRequestError('Name is missing');
      if (!phoneOk(r.phone)) throw new BadRequestError('The phone number is too short');
      if (!phoneOk(r.guardianPhone)) throw new BadRequestError('The guardian phone number is too short');
      if (!phoneOk(r.parentPhone)) throw new BadRequestError('The parent phone number is too short');
      if (r.idProofUrl && !r.idProofUrl.startsWith(`tenants/${tenantId}/students/id_proof/`)) throw new BadRequestError('The ID proof was not uploaded for this account');
      if (r.photoUrl && !r.photoUrl.startsWith(`tenants/${tenantId}/students/photo/`)) throw new BadRequestError('The photo was not uploaded for this account');
      // The same checks as the onboarding form (dates, phone lengths), before any room or bed is touched.
      const person = (daily ? dormitoryImportStudentSchema : tenant?.kind === TenantKind.ENTERPRISE ? employeeImportStudentSchema : hostelOnboardStudentSchema).parse({
        name: r.name,
        ...(r.email ? { email: r.email } : {}),
        ...(r.password ? { password: r.password } : {}),
        ...(r.phone ? { phone: r.phone } : {}),
        ...(r.guardianName ? { guardianName: r.guardianName } : {}),
        ...(r.guardianPhone ? { guardianPhone: r.guardianPhone } : {}),
        ...(r.parentName ? { parentName: r.parentName } : {}),
        ...(r.parentPhone ? { parentPhone: r.parentPhone } : {}),
        ...(r.address ? { address: r.address } : {}),
        ...(r.state ? { state: r.state } : {}),
        ...(r.city ? { city: r.city } : {}),
        ...(r.postalCode ? { postalCode: r.postalCode } : {}),
        ...(r.depositAmount != null ? { depositAmount: r.depositAmount } : {}),
        ...(r.depositPaid != null ? { depositPaid: r.depositPaid } : {}),
        ...(r.depositPaidAt ? { depositPaidAt: r.depositPaidAt } : {}),
        ...(r.depositMethod ? { depositMethod: r.depositMethod } : {}),
        ...(r.depositReference ? { depositReference: r.depositReference } : {}),
        ...(r.kycIdType ? { kycIdType: r.kycIdType } : {}),
        ...(r.kycIdNumber ? { kycIdNumber: r.kycIdNumber } : {}),
        ...(r.kycStatus ? { kycStatus: r.kycStatus } : {}),
        ...(r.idProofUrl ? { idProofUrl: r.idProofUrl } : {}),
        ...(r.photoUrl ? { photoUrl: r.photoUrl } : {}),
        ...(r.movedInAt || r.joinedOn ? { movedInAt: r.movedInAt || r.joinedOn } : {}),
        ...(await employeeColumns(r, employees)),
      });
      // Refuse duplicates before a requested room, bed or rate is created or
      // changed for the row. `onboardStudent` repeats this check for races and
      // for every manual creation path.
      await assertNoDuplicateStudent(person);
      if (!r.room) {
        await onboardStudent(person, actorId, property.id);
        results.push({ row, status: 'created', name: r.name });
        continue;
      }
      let room = await db.room.findFirst({ where: { propertyId: property.id, archivedAt: null, number: { equals: r.room, mode: 'insensitive' } } });
      if (!room) {
        const made = await createRoom({ propertyId: property.id, number: r.room, bedCount: 0, rateBasis: daily ? RateBasis.DAILY : RateBasis.MONTHLY, floor: r.floor ?? floorFromRoomNumber(r.room) });
        room = await db.room.findFirstOrThrow({ where: { id: made!.id } });
        roomsMade++;
      }
      const beds = await db.bed.findMany({ where: { roomId: room.id, archivedAt: null }, orderBy: { label: 'asc' } });
      let bed = r.bed ? beds.find((b) => b.label.toLowerCase() === r.bed!.toLowerCase()) : beds.find((b) => b.status === BedStatus.VACANT);
      if (!bed) {
        bed = await addBed(room.id, r.bed || nextBedLabel(beds.map((b) => b.label), daily));
        bedsMade++;
      }
      if (bed.status !== BedStatus.VACANT) throw new BadRequestError(`Bed ${bed.label} in room ${room.number} is not free`);
      if (r.rent != null) await setBedRent(bed.id, daily ? bed.monthlyRent : r.rent, undefined, daily ? r.rent : undefined);
      await onboardStudent({ ...person, bedId: bed.id }, actorId, property.id);
      results.push({ row, status: 'created', room: room.number, bed: bed.label, name: r.name });
    } catch (e) {
      const message = e instanceof AppError ? e.message : e instanceof ZodError ? `${e.issues[0]?.path.join('.') || 'Row'}: ${e.issues[0]?.message ?? 'not valid'}` : 'Could not import this row';
      results.push({ row, status: 'error', message, room: r.room ?? undefined, bed: r.bed ?? undefined, name: r.name });
    }
  }
  return { created: results.filter((x) => x.status === 'created').length, failed: results.filter((x) => x.status === 'error').length, roomsMade, bedsMade, results };
}

/**
 * Sprint 1 (TEPL): the employee columns of a row, as onboarding fields. The
 * department is named, so it is found or made; the shift is a code from the
 * shift list. Ignored where employee records are off.
 */
async function employeeColumns(r: Row, on: boolean) {
  if (!on) return {};
  const out: Record<string, string> = {};
  if (r.employeeCode) out.employeeCode = r.employeeCode;
  if (r.cardNumber) out.cardNumber = r.cardNumber;
  if (r.contractor) out.contractor = r.contractor;
  if (r.department) out.departmentId = await departmentByName(r.department);
  if (r.shift) {
    const shift = await db.shift.findFirst({ where: { code: { equals: r.shift, mode: 'insensitive' }, isActive: true }, select: { id: true } });
    if (!shift) throw new BadRequestError(`Shift ${r.shift} is not in the shift list`);
    out.defaultShiftId = shift.id;
  }
  return out;
}

export async function importStudentsHandler(req: Request, res: Response): Promise<void> {
  const { rows } = importRowsSchema.parse(req.body ?? {});
  res.json(await importStudents(rows, req.user!.sub, req.propertyId));
}
