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

/**
 * /api/medical (Sprint 6, TEPL). The employee's own record and consent; the
 * OHC's records, visits and appointments (OHC staff only — see the service);
 * the owner's overview and the access log (who looked, never what).
 */
export const medicalRouter = Router();
medicalRouter.use(authenticate, requireFeature('medical'));

const viewerOf = (req: Request): svc.Viewer => ({ userId: req.user!.sub, role: req.user!.role, perms: req.user!.perms });
const when = z.string().datetime().transform((v) => new Date(v));
const day = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).transform((v) => new Date(`${v}T00:00:00.000Z`));
const text = (max: number) => z.string().trim().max(max).nullable().optional();
const recordBody = z.object({
  bloodGroup: z.enum(['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']).nullable().optional(),
  allergies: text(500),
  conditions: z.array(z.string().trim().min(1).max(80)).max(30).optional(),
  medicines: z.array(z.object({ name: z.string().trim().min(1).max(80), dose: text(80), since: text(20) })).max(30).optional(),
  history: text(4000),
  fitness: z.object({ status: z.enum(['FIT', 'FIT_WITH_RESTRICTIONS', 'UNFIT']).nullable(), checkedOn: text(10), note: text(300) }).nullable().optional(),
  vaccinations: z.array(z.object({ name: z.string().trim().min(1).max(80), date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), dose: text(40) })).max(40).optional(),
  emergencyNotes: text(500),
});

// The employee.
medicalRouter.get('/me', authorize(Role.STUDENT), asyncHandler(async (req: Request, res: Response) => res.json(await svc.mine(req.user!.sub))));
medicalRouter.post('/me/consent', authorize(Role.STUDENT), asyncHandler(async (req: Request, res: Response) => res.json(await svc.consentMine(req.user!.sub))));
medicalRouter.delete('/me/consent', authorize(Role.STUDENT), asyncHandler(async (req: Request, res: Response) => res.json(await svc.withdrawMine(req.user!.sub))));

// The owner and the OHC: the overview and who looked (the service decides who sees records).
medicalRouter.use(propertyContext, requirePermission('MANAGE_MEDICAL'));
medicalRouter.get('/overview', asyncHandler(async (_req: Request, res: Response) => res.json(await svc.overview())));
medicalRouter.get('/access-log', asyncHandler(async (req: Request, res: Response) => {
  const q = z.object({ studentProfileId: z.string().uuid().optional(), days: z.coerce.number().int().min(1).max(365).default(30) }).parse(req.query);
  // Paged when asked (Sprint L3); otherwise the newest 1,000 as before.
  const pagination = getPagination(req.query);
  res.json(pagination ? await svc.pageAccessLog(q, pagination) : { entries: await svc.accessLog(q) });
}));

// The OHC.
medicalRouter.get('/people', asyncHandler(async (req: Request, res: Response) => {
  const q = z.string().trim().max(60).optional().parse(req.query.q);
  const pagination = getPagination(req.query);
  // `filter` (Sprint L4) narrows the pages on the server: consent, none or booked.
  const filter = z.enum(svc.PEOPLE_FILTERS).optional().parse(req.query.filter || undefined);
  res.json(pagination ? await svc.people(viewerOf(req), q || undefined, req.propertyId, pagination, filter) : { people: await svc.people(viewerOf(req), q, req.propertyId) });
}));
medicalRouter.get('/diary', asyncHandler(async (req: Request, res: Response) => {
  const days = z.coerce.number().int().min(1).max(60).default(14).parse(req.query.days ?? 14);
  const pagination = getPagination(req.query);
  res.json(pagination ? await svc.diary(viewerOf(req), days, pagination) : { appointments: await svc.diary(viewerOf(req), days) });
}));
medicalRouter.get('/records/:profileId', asyncHandler(async (req: Request, res: Response) => res.json(await svc.getRecord(viewerOf(req), req.params.profileId))));
medicalRouter.put('/records/:profileId', asyncHandler(async (req: Request, res: Response) => res.json(await svc.saveRecord(viewerOf(req), req.params.profileId, recordBody.parse(req.body)))));
medicalRouter.post('/records/:profileId/consent', asyncHandler(async (req: Request, res: Response) => res.json(await svc.recordPaperConsent(viewerOf(req), req.params.profileId))));
medicalRouter.post('/records/:profileId/visits', asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ at: when.optional(), complaint: z.string().trim().min(2).max(500), findings: text(1000), treatment: text(1000), advice: text(500), fitForDuty: z.boolean().nullable().optional(), followUpOn: day.nullable().optional() }).parse(req.body);
  res.status(201).json({ visit: await svc.addVisit(viewerOf(req), req.params.profileId, input) });
}));
medicalRouter.post('/records/:profileId/appointments', asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ at: when, purpose: z.string().trim().min(2).max(60), note: text(500) }).parse(req.body);
  res.status(201).json({ appointment: await svc.addAppointment(viewerOf(req), req.params.profileId, input) });
}));
medicalRouter.patch('/appointments/:id', asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ status: z.enum(['SCHEDULED', 'DONE', 'MISSED', 'CANCELLED']).optional(), at: when.optional() }).parse(req.body);
  res.json({ appointment: await svc.updateAppointment(viewerOf(req), req.params.id, input) });
}));
