import { Request, Response } from 'express';
import { z } from 'zod';
import {
  onboardStudentSchema,
  hostelOnboardStudentSchema,
  employeeOnboardStudentSchema,
  assignBedSchema,
  listStudentsQuerySchema,
  updateStudentSchema,
  updateMyPhotoSchema,
  resetStudentPasswordSchema,
  createStudentLoginSchema,
} from './students.schemas';
import { TenantKind } from '@prisma/client';
import * as svc from './students.service';
import { createStay } from '../stays/stays.service';
import * as billingRules from '../billing/billing-rules.service';
import * as collections from '../payments/collections.service';
import { db, prismaUnscoped } from '../../lib/prisma';
import { NotFoundError } from '../../lib/errors';
import { getPagination, getSearch } from '../../lib/pagination';
import { presignDownload } from '../uploads/uploads.service';
import { holdArrivalBed } from './employee-record';

export async function onboardStudent(req: Request, res: Response): Promise<void> {
  const tenant = req.user!.tenantId
    ? await prismaUnscoped.tenant.findUnique({ where: { id: req.user!.tenantId }, select: { kind: true } })
    : null;
  const input = (tenant?.kind === TenantKind.DORMITORY ? onboardStudentSchema : tenant?.kind === TenantKind.ENTERPRISE ? employeeOnboardStudentSchema : hostelOnboardStudentSchema).parse(req.body);
  // Sprint 1 (TEPL): the bed is held for their arrival rather than taken now.
  if (input.holdForArrival && input.bedId) {
    const { bedId, ...rest } = input;
    const made = await svc.onboardStudent(rest, req.user!.sub, req.propertyId);
    await holdArrivalBed(made.profile.id, bedId);
    res.status(201).json({ ...made, profile: await svc.getStudent(made.profile.id) });
    return;
  }
  res.status(201).json(await svc.onboardStudent(input, req.user!.sub, req.propertyId));
}

export async function studentStats(req: Request, res: Response): Promise<void> {
  res.json({ stats: await svc.studentStats(req.propertyId) });
}

export async function listStudents(req: Request, res: Response): Promise<void> {
  const pagination = getPagination(req.query);
  const { assigned } = listStudentsQuerySchema.parse(req.query);
  const result = await svc.listStudents(req.propertyId, pagination, {
    q: getSearch(req.query),
    assigned,
    departmentId: typeof req.query.departmentId === 'string' && z.string().uuid().safeParse(req.query.departmentId).success ? req.query.departmentId : undefined,
  });

  // Paginated callers get the envelope; everyone else the original array.
  res.json(pagination ? result : { students: result });
}

export async function createStudentLogin(req: Request, res: Response): Promise<void> {
  const { email, password } = createStudentLoginSchema.parse(req.body);
  await svc.createStudentLogin(req.params.id, email, password, req.propertyId);
  res.json({ ok: true });
}

export async function resetStudentPassword(req: Request, res: Response): Promise<void> {
  const { newPassword } = resetStudentPasswordSchema.parse(req.body);
  await svc.resetStudentPassword(req.params.id, newPassword, req.propertyId);
  res.status(204).send();
}

export async function updateMyPhoto(req: Request, res: Response): Promise<void> {
  const { photoUrl } = updateMyPhotoSchema.parse(req.body);
  res.json({ profile: await svc.updateMyPhoto(req.user!.sub, photoUrl) });
}

export async function getStudent(req: Request, res: Response): Promise<void> {
  res.json({ student: await svc.getStudent(req.params.id) });
}

export async function updateStudent(req: Request, res: Response): Promise<void> {
  const input = updateStudentSchema.parse(req.body);
  res.json({ profile: await svc.updateStudent(req.params.id, input) });
}

export async function deleteStudent(req: Request, res: Response): Promise<void> {
  await svc.deleteStudent(req.params.id);
  res.status(204).send();
}

export async function assignBed(req: Request, res: Response): Promise<void> {
  const { bedId, movedInAt, vacatedAt, checkIn, checkOut, amount } = assignBedSchema.parse(req.body);
  if (bedId && checkIn && checkOut) {
    // A dormitory booking: the stay reserves the bed for the window and, under a
    // per-night room, raises the invoice. The bed itself is taken at check-in.
    const stay = await createStay({ studentProfileId: req.params.id, bedId, checkIn: new Date(checkIn), checkOut: new Date(checkOut), amount }, req.user!.sub);
    const profile = await svc.getStudent(req.params.id, req.propertyId);
    return void res.json({ profile, stay });
  }
  const profile = bedId === null ? await svc.vacateBed(req.params.id, vacatedAt) : await svc.assignBed(req.params.id, bedId, movedInAt);
  res.json({ profile });
}

// ── One-off charges (billing rules, Sprint 1) ──────────────────────────────

const addChargeSchema = z.object({
  label: z.string().trim().min(2).max(80),
  amount: z.number().int().min(1).max(1000000),
  chargeTypeId: z.string().uuid().optional(),
  note: z.string().trim().max(200).optional(),
  date: z
    .string()
    .regex(/^\d{4}-\d{2}-\d{2}$/, 'date must be YYYY-MM-DD')
    .transform((v) => new Date(`${v}T12:00:00.000Z`))
    .optional(),
  // true: a standalone invoice today; false (default): carried into the next rent invoice.
  billNow: z.boolean().optional().default(false),
});

export async function listCharges(req: Request, res: Response): Promise<void> {
  await svc.getStudent(req.params.id, req.propertyId); // scoping: 404 outside the property
  res.json({ charges: await billingRules.listStudentCharges(req.params.id) });
}

export async function addCharge(req: Request, res: Response): Promise<void> {
  const input = addChargeSchema.parse(req.body);
  await svc.getStudent(req.params.id, req.propertyId);
  const result = await billingRules.addStudentCharge(req.params.id, input, req.user!.sub);
  res.status(201).json(result);
}

// ── Online collection (Sprint 3): virtual accounts and mandates ─────────────

export async function getVirtualAccount(req: Request, res: Response): Promise<void> {
  await svc.getStudent(req.params.id, req.propertyId);
  res.json({ virtualAccount: await collections.getVirtualAccount(req.params.id) });
}

export async function createVirtualAccount(req: Request, res: Response): Promise<void> {
  await svc.getStudent(req.params.id, req.propertyId);
  res.status(201).json({ virtualAccount: await collections.ensureVirtualAccount(req.params.id) });
}

export async function closeVirtualAccount(req: Request, res: Response): Promise<void> {
  await svc.getStudent(req.params.id, req.propertyId);
  res.json({ virtualAccount: await collections.closeVirtualAccountFor(req.params.id) });
}

const mandateSchema = z.object({
  mandateRef: z.string().trim().min(3).max(80).nullable(),
  mandateStatus: z.enum(['CREATED', 'AUTHENTICATED', 'ACTIVE', 'PAUSED', 'CANCELLED']).nullable().optional(),
});

async function saveMandate(profileId: string, input: z.infer<typeof mandateSchema>) {
  const data = input.mandateRef ? { mandateRef: input.mandateRef, mandateStatus: input.mandateStatus ?? 'CREATED', mandateSetAt: new Date() } : { mandateRef: null, mandateStatus: null, mandateSetAt: null };
  const row = await db.studentProfile.update({ where: { id: profileId }, data, select: { id: true, mandateRef: true, mandateStatus: true, mandateSetAt: true } });
  return row;
}

export async function setMandate(req: Request, res: Response): Promise<void> {
  const input = mandateSchema.parse(req.body);
  await svc.getStudent(req.params.id, req.propertyId);
  res.json({ mandate: await saveMandate(req.params.id, input) });
}

export async function setMyMandate(req: Request, res: Response): Promise<void> {
  const input = mandateSchema.parse(req.body);
  const profile = await db.studentProfile.findFirst({ where: { userId: req.user!.sub }, select: { id: true } });
  if (!profile) throw new NotFoundError('No student profile for this account');
  res.json({ mandate: await saveMandate(profile.id, input) });
}

/** Sprint 1 (TEPL): hold a bed until the employee's first punch, or release it (null). */
export async function holdArrival(req: Request, res: Response): Promise<void> {
  const { bedId } = z.object({ bedId: z.string().uuid().nullable() }).parse(req.body);
  await svc.getStudent(req.params.id, req.propertyId);
  await holdArrivalBed(req.params.id, bedId);
  res.json({ profile: await svc.getStudent(req.params.id, req.propertyId) });
}

export async function setBiometricId(req: Request, res: Response): Promise<void> {
  const { biometricId } = z.object({ biometricId: z.string().min(1).max(64).nullable() }).parse(req.body);
  res.json({ profile: await svc.setBiometricId(req.params.id, biometricId) });
}

export async function me(req: Request, res: Response): Promise<void> {
  res.json({ profile: await svc.getMyProfile(req.user!.sub) });
}

const updateMeSchema = z
  .object({
    guardianName: z.string().trim().max(120).nullable().optional(),
    guardianPhone: z.string().trim().max(20).nullable().optional(),
    parentName: z.string().trim().max(120).nullable().optional(),
    parentPhone: z.string().trim().max(20).nullable().optional(),
    address: z.string().trim().max(300).nullable().optional(),
    city: z.string().trim().max(80).nullable().optional(),
    state: z.string().trim().max(80).nullable().optional(),
    postalCode: z.string().trim().max(12).nullable().optional(),
    photoUrl: z.string().max(500).nullable().optional(),
  })
  .strict();

export async function updateMe(req: Request, res: Response): Promise<void> {
  const input = updateMeSchema.parse(req.body);
  res.json({ profile: await svc.updateMyProfile(req.user!.sub, input) });
}

/** A short-lived read URL for one of the student's OWN documents. */
export async function myDocUrl(req: Request, res: Response): Promise<void> {
  const doc = z.enum(['photo', 'idProof', 'addressProof', 'policeVerification', 'propertyLogo']).parse(req.query.doc);
  const key = await svc.myDocKey(req.user!.sub, doc);
  res.json({ url: key ? await presignDownload(req.user!.tenantId!, key) : null });
}
