import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { AssetCheckPhase, MoveOutStatus, 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 { getTenantIdOrThrow } from '../../lib/tenantContext';
import { ConflictError } from '../../lib/errors';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { getPagination } from '../../lib/pagination';
import * as svc from './moveouts.service';
import { buildSettlementPdf } from './settlement-pdf.service';
import * as notify from '../notifications/notifications.service';

/**
 * Move-outs: notice (MANAGE_STUDENTS) and the money (MANAGE_RENT). A warden
 * runs the queue and the checklist; the rent desk signs the settlement and
 * records the refund.
 */

const dayString = z
  .string()
  .regex(/^\d{4}-\d{2}-\d{2}$/, 'date must be YYYY-MM-DD')
  .transform((v) => new Date(`${v}T00:00:00.000Z`))
  .refine((d) => !Number.isNaN(d.getTime()), 'not a date');

const deductionSchema = z.object({
  label: z.string().trim().min(2).max(80),
  amount: z.coerce.number().int().min(0).max(1_000_000),
  note: z.string().trim().max(300).nullable().optional(),
  photoKey: z.string().max(500).nullable().optional(),
  fromCheck: z.boolean().optional(),
});
const checkItemSchema = z.object({
  key: z.string().trim().min(1).max(40),
  name: z.string().trim().max(60).optional(),
  charge: z.coerce.number().int().min(0).max(1_000_000).optional(),
  ok: z.boolean(),
  note: z.string().trim().max(200).nullable().optional(),
  photoKey: z.string().max(500).nullable().optional(),
});

const people = [authenticate, propertyContext, requirePermission('MANAGE_STUDENTS')] as const;
const money = [authenticate, propertyContext, requirePermission('MANAGE_RENT')] as const;

export const moveOutRouter = Router();

moveOutRouter.get(
  '/',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    const status = typeof req.query.status === 'string' && req.query.status in MoveOutStatus ? (req.query.status as MoveOutStatus) : undefined;
    // `page` asks for one column a page at a time (Sprint L3): `statuses` is a
    // comma list (a board column can hold two). Without it, the first 300 as before.
    const pagination = getPagination(req.query);
    if (pagination) {
      const listed = typeof req.query.statuses === 'string' ? req.query.statuses.split(',').filter((v): v is MoveOutStatus => v in MoveOutStatus) : status ? [status] : undefined;
      res.json(await svc.pageMoveOuts(req.propertyId, listed, pagination));
      return;
    }
    res.json(await svc.listMoveOuts(req.propertyId, status));
  }),
);

moveOutRouter.get(
  '/:id',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await svc.getMoveOut(req.params.id));
  }),
);

moveOutRouter.patch(
  '/:id',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ lastDay: dayString.optional(), reason: z.string().trim().max(300).nullable().optional() }).parse(req.body);
    res.json({ moveOut: await svc.updateMoveOut(req.params.id, input) });
  }),
);

moveOutRouter.post(
  '/:id/cancel',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ moveOut: await svc.cancelMoveOut(req.params.id) });
  }),
);

/** An employee hostel closes a move-out directly; everyone else goes through the settlement. */
moveOutRouter.post(
  '/:id/close',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    if (await tenantHasFeature(getTenantIdOrThrow(), 'billing')) throw new ConflictError('Record the settlement to close this move-out', 'NEEDS_SETTLEMENT');
    res.json({ moveOut: await svc.closeMoveOut(req.params.id) });
  }),
);

moveOutRouter.put(
  '/:id/settlement',
  ...money,
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ deductions: z.array(deductionSchema).max(50), promisedDate: dayString.optional(), notes: z.string().trim().max(1000).nullable().optional() }).parse(req.body);
    res.json({ moveOut: await svc.upsertSettlement(req.params.id, input) });
  }),
);

moveOutRouter.post(
  '/:id/share',
  ...money,
  asyncHandler(async (req: Request, res: Response) => {
    const moveOut = await svc.shareSettlement(req.params.id);
    res.json({ moveOut });
    const tenantId = getTenantIdOrThrow();
    notify.inBackground('settlement shared', () => notify.notifySettlementShared(tenantId, moveOut.id));
  }),
);

moveOutRouter.post(
  '/:id/reopen',
  ...money,
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ moveOut: await svc.reopenSettlement(req.params.id) });
  }),
);

moveOutRouter.post(
  '/:id/refund',
  ...money,
  asyncHandler(async (req: Request, res: Response) => {
    const input = z
      .object({
        amount: z.coerce.number().int().min(0).optional(),
        method: z.enum(['CASH', 'UPI', 'CARD', 'BANK_TRANSFER', 'CHEQUE', 'OTHER']),
        reference: z.string().trim().max(80).optional(),
        paidAt: dayString.optional(),
        note: z.string().trim().max(200).optional(),
      })
      .parse(req.body);
    res.json({ moveOut: await svc.recordRefund(req.params.id, input) });
  }),
);

moveOutRouter.get(
  '/:id/pdf',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    const { buffer, filename } = await buildSettlementPdf(req.params.id);
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.send(buffer);
  }),
);

// ── Student side ───────────────────────────────────────────────────────────

export const myMoveOutRouter = Router();
myMoveOutRouter.use(authenticate, authorize(Role.STUDENT));

myMoveOutRouter.get(
  '/move-out',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await svc.myMoveOut(req.user!.sub));
  }),
);

myMoveOutRouter.post(
  '/move-out',
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ lastDay: dayString, reason: z.string().trim().max(300).optional() }).parse(req.body);
    res.status(201).json(await svc.myStartMoveOut(req.user!.sub, input));
  }),
);

myMoveOutRouter.delete(
  '/move-out',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ moveOut: await svc.myCancelMoveOut(req.user!.sub) });
  }),
);

myMoveOutRouter.get(
  '/settlement',
  asyncHandler(async (req: Request, res: Response) => {
    const mine = await svc.myMoveOut(req.user!.sub);
    res.json({ settlement: mine.moveOut?.settlement ?? null, moveOut: mine.moveOut });
  }),
);

myMoveOutRouter.get(
  '/settlement/pdf',
  asyncHandler(async (req: Request, res: Response) => {
    const mine = await svc.myMoveOut(req.user!.sub);
    if (!mine.moveOut?.settlement?.sharedAt) {
      res.status(404).json({ error: 'No shared settlement yet' });
      return;
    }
    const { buffer, filename } = await buildSettlementPdf(mine.moveOut.id, { userId: req.user!.sub });
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.send(buffer);
  }),
);

myMoveOutRouter.post(
  '/settlement/dispute',
  asyncHandler(async (req: Request, res: Response) => {
    const { body } = z.object({ body: z.string().trim().min(10).max(2000) }).parse(req.body);
    res.status(201).json(await svc.disputeSettlement(req.user!.sub, body));
  }),
);

// ── Room asset templates (per property, MANAGE_ROOMS) and checks (MANAGE_STUDENTS) ──

export const assetTemplateRouter = Router();
const rooms = [authenticate, requirePermission('MANAGE_ROOMS')] as const;

assetTemplateRouter.get(
  '/:id/asset-template',
  ...rooms,
  asyncHandler(async (req: Request, res: Response) => {
    const roomType = typeof req.query.roomType === 'string' ? req.query.roomType : undefined;
    res.json({ template: await svc.getAssetTemplate(req.params.id, roomType), templates: await svc.listAssetTemplates(req.params.id) });
  }),
);

assetTemplateRouter.put(
  '/:id/asset-template',
  ...rooms,
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ roomType: z.string().trim().max(40).optional().default(''), items: z.array(z.object({ key: z.string().min(1).max(40), name: z.string().min(1).max(60), charge: z.coerce.number().int().min(0).max(1_000_000) })).max(60) }).parse(req.body);
    res.json({ template: await svc.putAssetTemplate(req.params.id, input.roomType, input.items) });
  }),
);

export const assetCheckRouter = Router();

assetCheckRouter.get(
  '/:id/asset-check',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    const checks = await svc.listAssetChecks(req.params.id);
    const student = await (await import('../students/students.service')).getStudent(req.params.id, req.propertyId);
    const template = await svc.getAssetTemplate(student.property?.id ?? student.propertyId ?? '', student.bed?.room?.type ?? null);
    res.json({ checks, template, proposedDeductions: checks.out ? svc.proposeDeductions(checks.in?.items ?? null, checks.out.items) : [] });
  }),
);

assetCheckRouter.post(
  '/:id/asset-check',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ phase: z.nativeEnum(AssetCheckPhase), items: z.array(checkItemSchema).min(1).max(60) }).parse(req.body);
    await (await import('../students/students.service')).getStudent(req.params.id, req.propertyId);
    res.status(201).json(await svc.recordAssetCheck(req.params.id, input.phase, input.items as svc.CheckedItem[], req.user!.sub));
  }),
);

// Office starts a move-out for a student.
export const startMoveOutRouter = Router();
startMoveOutRouter.post(
  '/:id/move-out',
  ...people,
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ lastDay: dayString, reason: z.string().trim().max(300).optional() }).parse(req.body);
    await (await import('../students/students.service')).getStudent(req.params.id, req.propertyId);
    res.status(201).json(await svc.startMoveOut(req.params.id, { ...input, by: 'OFFICE', userId: req.user!.sub }));
  }),
);
