import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { Role } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { authorize } from '../../middleware/authorize';
import { requireFeature } from '../../middleware/requireFeature';
import { requirePermission } from '../../middleware/requirePermission';
import { propertyContext } from '../../middleware/propertyContext';
import { ForbiddenError } from '../../lib/errors';
import * as svc from './leave.service';
import { getPagination } from '../../lib/pagination';

/**
 * /api/leave — the leave policy (Sprint 1, TEPL). Employees apply and see
 * their balances; the hostel decides the first step and plant approvers the
 * second. Plain leave requests still go through /api/requests.
 */
export const leaveRouter = Router();
leaveRouter.use(authenticate, requireFeature('leavePolicy'));

const dateStr = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'date must be YYYY-MM-DD');
const yearQ = (q: unknown) => (typeof q === 'string' && /^\d{4}$/.test(q) ? Number(q) : new Date().getUTCFullYear());
const approverOf = (req: Request): svc.Approver => ({ userId: req.user!.sub, role: req.user!.role, perms: req.user!.perms });

const typeSchema = z.object({
  code: z.string().trim().min(1).max(8).regex(/^[A-Za-z0-9]+$/, 'Letters and digits only'),
  name: z.string().trim().min(2).max(60),
  yearlyDays: z.number().min(0).max(366).nullable(),
  carryForwardMax: z.number().min(0).max(366),
  maxPerRequest: z.number().min(0.5).max(366).nullable(),
  noticeDays: z.number().int().min(0).max(90),
  halfDayAllowed: z.boolean(),
  needsPlantApproval: z.boolean(),
  certificateAfterDays: z.number().int().min(1).max(90).nullable(),
  isActive: z.boolean(),
});

// ── Employees ──
leaveRouter.get('/me', authorize(Role.STUDENT), asyncHandler(async (req: Request, res: Response) => {
  const year = yearQ(req.query.year);
  const [balances, leaves] = await Promise.all([svc.myBalances(req.user!.sub, year), svc.myLeaves(req.user!.sub)]);
  res.json({ year, balances, leaves });
}));
leaveRouter.post('/apply', authorize(Role.STUDENT), asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ leaveTypeId: z.string().uuid(), fromDate: dateStr, toDate: dateStr, halfDay: z.boolean().optional(), reason: z.string().trim().min(3).max(2000) }).parse(req.body);
  res.status(201).json({ leave: await svc.applyLeave(req.user!.sub, input) });
}));

// ── The policy ── (everyone signed in may read it: employees choose from it)
leaveRouter.get('/types', asyncHandler(async (req: Request, res: Response) => res.json({ types: await svc.listTypes(req.query.all === 'true' && req.user!.perms.includes('MANAGE_STUDENTS')) })));
leaveRouter.put('/types', requirePermission('MANAGE_STUDENTS'), asyncHandler(async (req: Request, res: Response) => {
  const { types } = z.object({ types: z.array(typeSchema).min(1).max(20) }).parse(req.body);
  res.json({ types: await svc.saveTypes(types) });
}));

// ── Approvals ──
leaveRouter.get('/approvals', propertyContext, asyncHandler(async (req: Request, res: Response) => {
  const stage = z.enum(['HOSTEL', 'PLANT']).parse(req.query.stage ?? 'HOSTEL');
  // Paged when asked (Sprint L3); otherwise the first 300 as before.
  const pagination = getPagination(req.query);
  res.json(pagination ? await svc.queue(approverOf(req), stage, req.propertyId, pagination) : { leaves: await svc.queue(approverOf(req), stage, req.propertyId) });
}));
leaveRouter.post('/:id/decide', asyncHandler(async (req: Request, res: Response) => {
  const { decision, note } = z.object({ decision: z.enum(['APPROVE', 'REJECT']), note: z.string().trim().max(300).optional() }).parse(req.body);
  if (req.user!.role === Role.STUDENT) throw new ForbiddenError('Employees cannot decide leave');
  res.json({ leave: await svc.decide(req.params.id, approverOf(req), decision, note) });
}));

// ── Calendar and balances, for the hostel ──
leaveRouter.get('/calendar', propertyContext, requirePermission('MANAGE_STUDENTS'), asyncHandler(async (req: Request, res: Response) => {
  const q = z.object({ from: dateStr, to: dateStr, departmentId: z.string().uuid().optional() }).parse(req.query);
  res.json({ leaves: await svc.calendar(new Date(`${q.from}T00:00:00Z`), new Date(`${q.to}T00:00:00Z`), { propertyId: req.propertyId, departmentId: q.departmentId }) });
}));
leaveRouter.get('/balances/:profileId', requirePermission('MANAGE_STUDENTS'), asyncHandler(async (req: Request, res: Response) => {
  const year = yearQ(req.query.year);
  res.json({ year, balances: await svc.balances(req.params.profileId, year) });
}));
leaveRouter.put('/balances/:profileId', requirePermission('MANAGE_STUDENTS'), asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ leaveTypeId: z.string().uuid(), year: z.number().int().min(2020).max(2100), adjustment: z.number().min(-366).max(366), note: z.string().trim().max(200).nullable().optional() }).parse(req.body);
  res.json({ year: input.year, balances: await svc.setAdjustment(req.params.profileId, input.leaveTypeId, input.year, input.adjustment, input.note ?? null) });
}));
