import { requireFeature, tenantHasFeature } from '../../middleware/requireFeature';
import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { PassStatus, PunchDirection, Role } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { authorize } from '../../middleware/authorize';
import { requirePermission } from '../../middleware/requirePermission';
import { propertyContext } from '../../middleware/propertyContext';
import { BadRequestError } from '../../lib/errors';
import { getPagination, getSearch } from '../../lib/pagination';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import * as gate from './gate.service';
import * as visitors from './visitors.service';
import * as guardians from './guardians.service';
import { getMyDues, getMyDuesStats, getMyPayments } from '../billing/billing.service';
import { buildInvoicePdf } from '../billing/invoice-pdf.service';
import { myMoveOut } from '../moveouts/moveouts.service';
import { buildSettlementPdf } from '../moveouts/settlement-pdf.service';

const dateish = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'date must be YYYY-MM-DD');
const whenish = z.string().datetime({ offset: true }).or(dateish.transform((d) => `${d}T00:00:00.000Z`));

const gateStaff = [authenticate, propertyContext, requirePermission('MANAGE_GATE')] as const;
// The pass desk. A dormitory has no gate feature, but app builds already in
// the store still call these routes for one, so they are not refused yet;
// the clients hide them. Add requireFeature('gate') once those builds retire.
const passDesk = [...gateStaff] as const;
const attendanceStaff = [authenticate, propertyContext, requirePermission('VIEW_ATTENDANCE')] as const;

// ── /api/passes ──────────────────────────────────────────────────────────────
export const passRouter = Router();
export const gateRouter = Router();
const gateRouterLate = gateRouter;

passRouter.get(
  '/me',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ passes: await gate.myPasses(req.user!.sub) });
  }),
);

/** The QR for a pass: the student's own, or any in the property for gate staff. Each call rotates the token. */
passRouter.get(
  '/:id/qr',
  authenticate,
  asyncHandler(async (req: Request, res: Response) => {
    if (req.user!.role === Role.STUDENT) {
      res.json(await gate.rotateQr(req.params.id, { studentUserId: req.user!.sub }));
      return;
    }
    if (!(req.user!.perms ?? []).includes('MANAGE_GATE') && !(req.user!.perms ?? []).includes('MANAGE_STUDENTS')) throw new BadRequestError('Requires permission: MANAGE_GATE', 'FORBIDDEN');
    res.json(await gate.rotateQr(req.params.id));
  }),
);

passRouter.get(
  '/',
  ...passDesk,
  asyncHandler(async (req: Request, res: Response) => {
    const status = typeof req.query.status === 'string' && req.query.status in PassStatus ? (req.query.status as PassStatus) : undefined;
    // `page` asks for the paged envelope (Sprint L2); without it the reply is the
    // newest 100 as before, which the builds on phones still read.
    const pagination = getPagination(req.query);
    if (!pagination) {
      res.json({ passes: await gate.listPasses(req.propertyId, { status }) });
      return;
    }
    const range = z.object({ from: dateish.optional(), to: dateish.optional() }).parse(req.query);
    res.json(await gate.pagePasses(req.propertyId, { status, ...range, q: getSearch(req.query) }, pagination));
  }),
);

/** Extend or shorten a pass. A return time moved into the past is picked up by the next late-return tick. */
passRouter.patch(
  '/:id',
  ...passDesk,
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ validFrom: z.string().datetime({ offset: true }).optional(), validTo: z.string().datetime({ offset: true }).optional(), destination: z.string().trim().max(120).nullable().optional() }).parse(req.body);
    res.json({ pass: await gate.updatePass(req.params.id, { validFrom: input.validFrom ? new Date(input.validFrom) : undefined, validTo: input.validTo ? new Date(input.validTo) : undefined, destination: input.destination }) });
  }),
);

/** The hourly late-return pass, on demand. */
gateRouterLate.post(
  '/late-returns/run',
  ...passDesk,
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ result: await gate.flagLateReturns() });
  }),
);

passRouter.post(
  '/:id/cancel',
  ...passDesk,
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ pass: await gate.cancelPass(req.params.id) });
  }),
);

// ── /api/gate — the guard's screen ───────────────────────────────────────────

gateRouter.post(
  '/scan',
  ...gateStaff,
  asyncHandler(async (req: Request, res: Response) => {
    const { qr } = z.object({ qr: z.string().min(10).max(200) }).parse(req.body);
    res.json(await gate.scan(qr));
  }),
);

gateRouter.post(
  '/punch',
  ...gateStaff,
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ passId: z.string().uuid().optional(), studentProfileId: z.string().uuid().optional(), direction: z.nativeEnum(PunchDirection), note: z.string().trim().max(200).optional() }).parse(req.body);
    res.status(201).json(await gate.punch(input, req.user!.sub));
  }),
);

gateRouter.get(
  '/summary',
  ...gateStaff,
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await gate.gateSummary(req.propertyId));
  }),
);

gateRouter.get(
  '/tonight',
  ...attendanceStaff,
  asyncHandler(async (req: Request, res: Response) => {
    // `page` sends the rows a page at a time (Sprint L3), with the same summary; without it, everyone as before.
    const pagination = getPagination(req.query);
    if (pagination) {
      const status = z.enum(gate.TONIGHT_FILTERS).optional().parse(req.query.status || undefined);
      res.json(await gate.pageTonight(req.propertyId, { status, q: getSearch(req.query) }, pagination));
      return;
    }
    res.json(await gate.tonight(req.propertyId));
  }),
);

/** The guard's student lookup for a walk-in without a QR: name search within the property. */
gateRouter.get(
  '/students',
  ...gateStaff,
  asyncHandler(async (req: Request, res: Response) => {
    const q = typeof req.query.q === 'string' ? req.query.q.trim() : '';
    if (q.length < 2) {
      res.json({ students: [] });
      return;
    }
    // Sprint 2 (TEPL): an employee hostel's guard also finds people by employee ID or card.
    const byEmployee = !!req.user?.tenantId && (await tenantHasFeature(req.user.tenantId, 'employeeRecords'));
    const rows = await db.studentProfile.findMany({
      where: {
        ...(req.propertyId ? { propertyId: req.propertyId } : {}),
        bedId: { not: null },
        ...(byEmployee
          ? { OR: [{ user: { name: { contains: q, mode: 'insensitive' } } }, { employeeCode: { contains: q, mode: 'insensitive' } }, { cardNumber: { contains: q, mode: 'insensitive' } }] }
          : { user: { name: { contains: q, mode: 'insensitive' } } }),
      },
      include: { user: { select: { name: true } }, bed: { include: { room: { select: { number: true } } } } },
      take: 10,
    });
    res.json({ students: rows.map((s) => ({ id: s.id, name: s.user.name, room: s.bed ? `Room ${s.bed.room.number} · Bed ${s.bed.label}` : null })) });
  }),
);

gateRouter.get(
  '/attendance/:studentId',
  ...attendanceStaff,
  asyncHandler(async (req: Request, res: Response) => {
    const s = await db.studentProfile.findFirst({ where: { id: req.params.studentId }, select: { id: true, property: { select: { curfewTime: true } } } });
    if (!s) throw new BadRequestError('Student not found', 'NOT_FOUND');
    res.json(await gate.attendanceFor(s.id, 30, s.property?.curfewTime ?? '22:00'));
  }),
);

// ── /api/students/me/attendance — the student's own strip ────────────────────
export const myGateRouter = Router();
myGateRouter.get(
  '/attendance',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await gate.myAttendance(req.user!.sub));
  }),
);

// ── /api/visitors ────────────────────────────────────────────────────────────
export const visitorRouter = Router();

const visitorSchema = z.object({
  name: z.string().trim().min(2).max(80),
  phone: z.string().trim().min(7).max(20).optional(),
  idType: z.enum(['AADHAAR', 'PAN', 'DRIVING_LICENCE', 'VOTER_ID', 'PASSPORT', 'OTHER']).optional(),
  idLast4: z.string().regex(/^[A-Za-z0-9]{4}$/).optional(),
  photoKey: z.string().max(500).optional(),
  purpose: z.string().trim().max(120).optional(),
  studentProfileId: z.string().uuid().optional(),
  expectedFrom: whenish.optional(),
  expectedTo: whenish.optional(),
});

visitorRouter.post(
  '/me',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    const input = visitorSchema.parse(req.body);
    res.status(201).json({ visitor: await visitors.preRegister(req.user!.sub, { ...input, expectedFrom: input.expectedFrom ? new Date(input.expectedFrom) : undefined, expectedTo: input.expectedTo ? new Date(input.expectedTo) : undefined }) });
  }),
);
visitorRouter.get(
  '/me',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ visitors: await visitors.myVisitors(req.user!.sub) });
  }),
);
visitorRouter.delete(
  '/me/:id',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ visitor: await visitors.cancelMyVisitor(req.user!.sub, req.params.id) });
  }),
);

visitorRouter.get(
  '/',
  ...gateStaff,
  asyncHandler(async (req: Request, res: Response) => {
    const date = typeof req.query.date === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(req.query.date) ? req.query.date : visitors.istDay();
    const status = typeof req.query.status === 'string' ? req.query.status : undefined;
    // Paged within the day when asked (Sprint L2); the date travels with the page.
    const pagination = getPagination(req.query);
    if (pagination) {
      res.json({ date, ...(await visitors.pageVisitors(req.propertyId, date, status, pagination)) });
      return;
    }
    res.json({ date, visitors: await visitors.listVisitors(req.propertyId, date, status) });
  }),
);

/** Sprint 4 (TEPL): the visitor report over a range, and who gets the most visitors. */
visitorRouter.get(
  '/report',
  ...gateStaff,
  requireFeature('visitorReports'),
  asyncHandler(async (req: Request, res: Response) => {
    const q = z.object({ from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/) }).parse(req.query);
    res.json(await visitors.visitorReport(req.propertyId, q.from, q.to));
  }),
);

visitorRouter.get(
  '/export',
  ...gateStaff,
  asyncHandler(async (req: Request, res: Response) => {
    const date = typeof req.query.date === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(req.query.date) ? req.query.date : visitors.istDay();
    res.setHeader('Content-Type', 'text/csv; charset=utf-8');
    res.setHeader('Content-Disposition', `attachment; filename="visitors-${date}.csv"`);
    res.send(await visitors.visitorsCsv(req.propertyId, date));
  }),
);

visitorRouter.post(
  '/',
  ...gateStaff,
  asyncHandler(async (req: Request, res: Response) => {
    const input = visitorSchema.parse(req.body);
    const propertyId = req.propertyId ?? (await db.property.findFirst({ orderBy: { createdAt: 'asc' }, select: { id: true } }))?.id;
    if (!propertyId) throw new BadRequestError('No property to log the visitor against');
    res.status(201).json({ visitor: await visitors.logVisitor(propertyId, { ...input, expectedFrom: undefined, expectedTo: undefined }, req.user!.sub) });
  }),
);

visitorRouter.post(
  '/:id/arrived',
  ...gateStaff,
  asyncHandler(async (req: Request, res: Response) => {
    const patch = visitorSchema.pick({ idType: true, idLast4: true, photoKey: true, phone: true }).parse(req.body ?? {});
    res.json({ visitor: await visitors.markArrived(req.params.id, patch, req.user!.sub) });
  }),
);

visitorRouter.post(
  '/:id/left',
  ...gateStaff,
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ visitor: await visitors.markLeft(req.params.id) });
  }),
);

// ── Guardians: office side (/api/students/:id/guardians) ─────────────────────
export const studentGuardianRouter = Router();
const people = [authenticate, propertyContext, requirePermission('MANAGE_STUDENTS')] as const;

studentGuardianRouter.get(
  '/:id/guardians',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ guardians: await guardians.listGuardians(req.params.id) });
  }),
);
studentGuardianRouter.post(
  '/:id/guardians',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ name: z.string().trim().min(2).max(120), email: z.string().email(), phone: z.string().trim().min(7).max(20).optional(), relation: z.string().trim().max(40).optional() }).parse(req.body);
    res.status(201).json(await guardians.addGuardian(req.params.id, input, req.user!.sub));
  }),
);
studentGuardianRouter.delete(
  '/:id/guardians/:linkId',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await guardians.removeGuardian(req.params.id, req.params.linkId));
  }),
);

// ── /api/guardian — the guardian's own, read-only portal ─────────────────────
export const guardianRouter = Router();
guardianRouter.use(authenticate, authorize(Role.GUARDIAN));

guardianRouter.get(
  '/students',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ students: await guardians.studentsForGuardian(req.user!.sub) });
  }),
);

/** Resolve the student's user id after the scope check — the read services are keyed by user. */
async function studentUser(req: Request): Promise<{ profileId: string; userId: string }> {
  await guardians.assertGuardianOf(req.user!.sub, req.params.studentId);
  const s = await db.studentProfile.findFirst({ where: { id: req.params.studentId }, select: { id: true, userId: true } });
  if (!s) throw new BadRequestError('Student not found', 'NOT_FOUND');
  return { profileId: s.id, userId: s.userId };
}

guardianRouter.get(
  '/students/:studentId/dues',
  asyncHandler(async (req: Request, res: Response) => {
    const { userId } = await studentUser(req);
    const [invoices, stats, payments] = await Promise.all([getMyDues(userId), getMyDuesStats(userId), getMyPayments(userId)]);
    res.json({ invoices, stats, payments });
  }),
);
guardianRouter.get(
  '/students/:studentId/invoices/:id/pdf',
  asyncHandler(async (req: Request, res: Response) => {
    const { userId } = await studentUser(req);
    const { buffer, filename } = await buildInvoicePdf(req.params.id, { userId });
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.send(buffer);
  }),
);
guardianRouter.get(
  '/students/:studentId/attendance',
  asyncHandler(async (req: Request, res: Response) => {
    const { profileId } = await studentUser(req);
    const s = await db.studentProfile.findFirst({ where: { id: profileId }, select: { property: { select: { curfewTime: true } } } });
    res.json(await gate.attendanceFor(profileId, 30, s?.property?.curfewTime ?? '22:00'));
  }),
);
guardianRouter.get(
  '/students/:studentId/passes',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ passes: await guardians.guardianPasses(req.user!.sub, req.params.studentId) });
  }),
);
guardianRouter.post(
  '/passes/:id/approve',
  asyncHandler(async (req: Request, res: Response) => {
    const { note } = z.object({ note: z.string().trim().max(300).optional() }).parse(req.body ?? {});
    res.json({ pass: await guardians.decidePass(req.user!.sub, req.params.id, true, note) });
  }),
);
guardianRouter.post(
  '/passes/:id/decline',
  asyncHandler(async (req: Request, res: Response) => {
    const { note } = z.object({ note: z.string().trim().min(3).max(300) }).parse(req.body);
    res.json({ pass: await guardians.decidePass(req.user!.sub, req.params.id, false, note) });
  }),
);
guardianRouter.get(
  '/students/:studentId/notices',
  asyncHandler(async (req: Request, res: Response) => {
    await studentUser(req);
    const notices = await db.notice.findMany({ orderBy: { createdAt: 'desc' }, take: 30, select: { id: true, title: true, body: true, category: true, important: true, createdAt: true } });
    res.json({ notices });
  }),
);
guardianRouter.get(
  '/students/:studentId/settlement',
  asyncHandler(async (req: Request, res: Response) => {
    const { userId } = await studentUser(req);
    const mine = await myMoveOut(userId);
    res.json({ settlement: mine.moveOut?.settlement ?? null, moveOut: mine.moveOut, residencyStatus: mine.residencyStatus });
  }),
);
guardianRouter.get(
  '/students/:studentId/settlement/pdf',
  asyncHandler(async (req: Request, res: Response) => {
    const { userId } = await studentUser(req);
    const mine = await myMoveOut(userId);
    if (!mine.moveOut?.settlement?.sharedAt) {
      res.status(404).json({ error: 'No shared settlement yet' });
      return;
    }
    const { buffer, filename } = await buildSettlementPdf(mine.moveOut.id, { userId });
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.send(buffer);
  }),
);

/** The tenant id for the guardian's session: for completeness in error paths. */
export const guardianTenant = () => getTenantIdOrThrow();
