import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { MessBillingMode, MessComplaintStatus, Role, StockDirection } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { authorize } from '../../middleware/authorize';
import { requirePermission } from '../../middleware/requirePermission';
import { requireFeature } from '../../middleware/requireFeature';
import { propertyContext } from '../../middleware/propertyContext';
import { isValidPeriod } from '../../lib/period';
import { getPagination, getSearch } from '../../lib/pagination';
import { BadRequestError, ForbiddenError } from '../../lib/errors';
import * as svc from './mess.service';
import * as cal from './calendar.service';
import * as inv from './inventory.service';
import * as complaints from './complaints.service';
import * as optout from './optout.service';

const menuSchema = z.object({
  breakfast: z.string().max(200).nullable().optional(),
  lunch: z.string().max(200).nullable().optional(),
  dinner: z.string().max(200).nullable().optional(),
  snacks: z.string().max(200).nullable().optional(),
});
const dateStr = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'date must be YYYY-MM-DD');
const feeSchema = z
  .object({
    messMonthlyFee: z.coerce.number().int().min(0).max(1_000_000).optional(),
    messBillingMode: z.nativeEnum(MessBillingMode).optional(),
    messDailyRate: z.coerce.number().int().min(0).max(100_000).optional(),
    // Sprint 6: student meal opt-out. Additive; every field optional.
    messOptOutEnabled: z.boolean().optional(),
    messOptOutCutoff: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'cutoff must be HH:MM').optional(),
    messMinRebateDays: z.coerce.number().int().min(1).max(31).optional(),
    messBreakfastWeight: z.coerce.number().int().min(0).max(100).optional(),
    messLunchWeight: z.coerce.number().int().min(0).max(100).optional(),
    messDinnerWeight: z.coerce.number().int().min(0).max(100).optional(),
  })
  .refine(
    (v) => {
      const w = [v.messBreakfastWeight, v.messLunchWeight, v.messDinnerWeight];
      if (w.every((x) => x === undefined)) return true;
      return w.every((x) => x !== undefined) && w.reduce((n, x) => n + (x ?? 0), 0) === 100;
    },
    { message: 'Meal weights must be sent together and add up to 100' },
  );
const optOutSchema = z.object({
  date: dateStr,
  meals: z.object({ BREAKFAST: z.boolean().optional(), LUNCH: z.boolean().optional(), DINNER: z.boolean().optional() }),
});
const daySchema = z.object({
  breakfast: z.string().max(200).nullable().optional(),
  lunch: z.string().max(200).nullable().optional(),
  dinner: z.string().max(200).nullable().optional(),
  isHoliday: z.boolean().optional(),
  note: z.string().max(200).nullable().optional(),
});
const holidaySchema = z.object({
  from: dateStr,
  to: dateStr,
  isHoliday: z.boolean().default(true),
  note: z.string().max(200).optional(),
});
const applySchema = z.object({ period: z.string(), overwrite: z.boolean().default(false) });
const itemSchema = z.object({
  name: z.string().min(1).max(80),
  unit: z.enum(['kg', 'litre', 'packet', 'dozen', 'piece']),
  reorderLevel: z.coerce.number().min(0).max(100_000).optional(),
});
const entrySchema = z.object({
  itemId: z.string().uuid(),
  direction: z.nativeEnum(StockDirection),
  quantity: z.coerce.number().positive().max(100_000),
  cost: z.coerce.number().int().min(0).max(10_000_000).optional(),
  reason: z.enum(['USAGE', 'WASTAGE', 'ADJUSTMENT']).optional(),
  date: dateStr,
  note: z.string().max(200).optional(),
});
const complaintSchema = z.object({
  category: z.enum(['FOOD_QUALITY', 'HYGIENE', 'QUANTITY', 'TIMING', 'OTHER']),
  subject: z.string().min(3).max(120),
  body: z.string().min(3).max(2000),
});
const replySchema = z.object({ body: z.string().min(1).max(2000) });
const statusSchema = z.object({ status: z.nativeEnum(MessComplaintStatus) });
const adminAttendanceSchema = z.object({ studentProfileId: z.string().uuid(), date: dateStr, present: z.boolean() });

export const messRouter = Router();


// Menu — anyone signed in can view; only Mess Admin edits.
messRouter.get('/menu', authenticate, asyncHandler(async (_req, res) => res.json({ menu: await svc.getMenu() })));
// The week from a sheet; the browser reads the file and sends the days.
const mealCell = z.string().trim().max(200).nullable().transform((v) => v || null);
const menuImportSchema = z.object({
  days: z
    .array(z.object({ dayOfWeek: z.number().int().min(0).max(6), breakfast: mealCell, lunch: mealCell, dinner: mealCell, snacks: mealCell.optional() }))
    .min(1)
    .max(7)
    .refine((days) => new Set(days.map((d) => d.dayOfWeek)).size === days.length, 'Each day can appear only once'),
});
messRouter.post(
  '/menu/import',
  authenticate,
  requireFeature('canteen'),
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ menu: await svc.importMenu(menuImportSchema.parse(req.body).days) });
  }),
);
messRouter.put(
  '/menu/:dayOfWeek',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const day = Number(req.params.dayOfWeek);
    if (!Number.isInteger(day) || day < 0 || day > 6) throw new BadRequestError('dayOfWeek must be 0–6');
    res.json({ menu: await svc.setMenu(day, menuSchema.parse(req.body)) });
  }),
);

// Mess fee setting — Mess Admin (Hostel Admin can view).
messRouter.get(
  '/settings',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (_req, res) => res.json({ settings: await svc.getSettings() })),
);
messRouter.put(
  '/settings',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ settings: await svc.setMessSettings(feeSchema.parse(req.body)) });
  }),
);

// ── Dated calendar ────────────────────────────────────────────────────────
// Anyone signed in may READ it — a student needs to know what is for dinner
// and when the mess is shut. Only MANAGE_MESS writes.
messRouter.get(
  '/calendar',
  authenticate,
  asyncHandler(async (req: Request, res: Response) => {
    const period = String(req.query.period ?? '');
    if (!isValidPeriod(period)) throw new BadRequestError('period (YYYY-MM) is required');
    res.json({ days: await cal.getCalendar(period) });
  }),
);
messRouter.put(
  '/calendar/:date',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const date = dateStr.parse(req.params.date);
    res.json({ day: await cal.setDay(date, daySchema.parse(req.body)) });
  }),
);
messRouter.post(
  '/calendar/apply-template',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const { period, overwrite } = applySchema.parse(req.body);
    if (!isValidPeriod(period)) throw new BadRequestError('period (YYYY-MM) is required');
    res.json(await cal.applyTemplate(period, overwrite));
  }),
);
messRouter.post(
  '/calendar/holidays',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const { from, to, isHoliday, note } = holidaySchema.parse(req.body);
    res.json(await cal.setHolidays(from, to, isHoliday, note));
  }),
);

// ── Who is on the mess ────────────────────────────────────────────────────
messRouter.get(
  '/subscribers',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const subscribed =
      req.query.subscribed === 'true' ? true : req.query.subscribed === 'false' ? false : undefined;
    const pagination = getPagination(req.query);
    const result = await cal.listSubscribers(
      req.propertyId,
      { q: getSearch(req.query), subscribed },
      pagination,
    );
    res.json(pagination ? result : { students: result });
  }),
);
/**
 * How many are on the mess in the active property, and of how many (Sprint
 * L1): the dashboard's tile, which used to download every subscriber and, in
 * an Enterprise tenant, every resident too. The list above stays tenant-wide,
 * as builds in the store read it; this count follows the property switcher.
 */
messRouter.get(
  '/subscribers/count',
  authenticate,
  propertyContext,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ counts: await cal.countSubscribers(req.propertyId) });
  }),
);
messRouter.post(
  '/subscribers/:studentProfileId',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const { startDate } = z.object({ startDate: dateStr }).parse(req.body);
    res.json({ subscription: await cal.subscribe(req.params.studentProfileId, startDate) });
  }),
);
messRouter.delete(
  '/subscribers/:studentProfileId',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const { endDate } = z.object({ endDate: dateStr }).parse(req.body);
    res.json({ subscription: await cal.unsubscribe(req.params.studentProfileId, endDate) });
  }),
);

// Attendance — the MESS ADMIN marks a student off for a day. Students do not
// mark themselves: retrospective edits after the bill lands are the single
// biggest source of mess-billing disputes.
messRouter.put(
  '/attendance',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const { studentProfileId, date, present } = adminAttendanceSchema.parse(req.body);
    res.json({ attendance: await svc.setStudentAttendance(studentProfileId, date, present) });
  }),
);
messRouter.get(
  '/absences',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const period = String(req.query.period ?? '');
    if (!isValidPeriod(period)) throw new BadRequestError('period (YYYY-MM) is required');
    res.json({ absences: await svc.getAbsencesForMonth(period) });
  }),
);
// ── Student meal opt-out (Sprint 6) ───────────────────────────────────────
// Off until the hostel enables it; bounded by the cutoff the day before.
messRouter.get(
  '/opt-out/me',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ optOut: await optout.myOptOuts(req.user!.sub, String(req.query.period ?? '')) });
  }),
);
messRouter.put(
  '/opt-out/me',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ day: await optout.setMyOptOut(req.user!.sub, optOutSchema.parse(req.body)) });
  }),
);
/** Plates to cook on a date: subscribers minus day-offs minus each meal's opt-outs. */
messRouter.get(
  '/headcount',
  authenticate,
  propertyContext,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const date = dateStr.parse(String(req.query.date ?? new Date(Date.now() + 86_400_000).toISOString().slice(0, 10)));
    res.json({ headcount: await optout.headcount(date, req.propertyId) });
  }),
);

messRouter.get(
  '/attendance/me',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) => {
    const period = String(req.query.period ?? '');
    if (!isValidPeriod(period)) throw new BadRequestError('period (YYYY-MM) is required');
    res.json({ attendance: await svc.getMyAttendance(req.user!.sub, period) });
  }),
);


// ── Inventory ─────────────────────────────────────────────────────────────
// Quantities are derived from the entry ledger, and a purchase writes a MESS
// expense at the same time, so stock and P&L cannot tell different stories.
messRouter.get(
  '/inventory',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const pagination = getPagination(req.query);
    const result = await inv.listItems(
      { q: getSearch(req.query), needsReorder: req.query.needsReorder === 'true' },
      pagination,
    );
    res.json(pagination ? result : { items: result });
  }),
);
// Sprint L2: the store's cards and shopping list, summed by the server.
messRouter.get(
  '/inventory/totals',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ totals: await inv.storeTotals() });
  }),
);
messRouter.post(
  '/inventory',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => res.status(201).json({ item: await inv.createItem(itemSchema.parse(req.body)) })),
);
messRouter.patch(
  '/inventory/:id',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) =>
    res.json({ item: await inv.updateItem(req.params.id, itemSchema.partial().extend({ isArchived: z.boolean().optional() }).parse(req.body)) }),
  ),
);
messRouter.delete(
  '/inventory/:id',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    await inv.archiveItem(req.params.id);
    res.status(204).send();
  }),
);

messRouter.get(
  '/stock',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const itemId = typeof req.query.itemId === 'string' ? req.query.itemId : undefined;
    const from = typeof req.query.from === 'string' ? cal.dayFrom(req.query.from) : undefined;
    const to = typeof req.query.to === 'string' ? cal.dayFrom(req.query.to) : undefined;
    const direction =
      req.query.direction === 'IN' || req.query.direction === 'OUT'
        ? (req.query.direction as StockDirection)
        : undefined;
    const pagination = getPagination(req.query);
    const result = await inv.listEntries(
      { itemId, from, to, direction, q: getSearch(req.query) },
      pagination,
    );
    res.json(pagination ? result : { entries: result });
  }),
);
messRouter.post(
  '/stock',
  authenticate,
  propertyContext,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    const input = entrySchema.parse(req.body);
    const entry = await inv.addEntry({
      ...input,
      date: cal.dayFrom(input.date),
      recordedById: req.user!.sub,
      propertyId: req.propertyId,
    });
    res.status(201).json({ entry });
  }),
);
messRouter.delete(
  '/stock/:id',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) => {
    await inv.deleteEntry(req.params.id);
    res.status(204).send();
  }),
);

// ── Complaints ────────────────────────────────────────────────────────────
// Students raise and see only their own; MANAGE_MESS sees the queue.
messRouter.post(
  '/complaints',
  authenticate,
  authorize(Role.STUDENT),
  asyncHandler(async (req: Request, res: Response) =>
    res.status(201).json({ complaint: await complaints.raiseComplaint(req.user!.sub, complaintSchema.parse(req.body)) }),
  ),
);
messRouter.get(
  '/complaints',
  authenticate,
  asyncHandler(async (req: Request, res: Response) => {
    const pagination = getPagination(req.query);
    const q = getSearch(req.query);
    const status = typeof req.query.status === 'string' ? (req.query.status as MessComplaintStatus) : undefined;
    const category = typeof req.query.category === 'string' ? req.query.category : undefined;

    // A student's own thread is scoped by the account, not by a query the
    // client sends — the filters narrow within that, never past it.
    if (req.user!.role === Role.STUDENT) {
      const mine = await complaints.listComplaints(
        { mineForUserId: req.user!.sub, status, category, q },
        pagination,
      );
      return res.json(pagination ? mine : { complaints: mine });
    }
    if (!req.user!.perms?.includes('MANAGE_MESS')) throw new ForbiddenError('You do not have permission to read mess complaints');
    const result = await complaints.listComplaints({ status, category, q }, pagination);
    res.json(pagination ? result : { complaints: result });
  }),
);
messRouter.get(
  '/complaints/summary',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (_req, res) => res.json({ summary: await complaints.complaintSummary() })),
);
messRouter.get(
  '/complaints/:id',
  authenticate,
  asyncHandler(async (req: Request, res: Response) => {
    const viewer = { userId: req.user!.sub, role: req.user!.role };
    if (viewer.role !== Role.STUDENT && !req.user!.perms?.includes('MANAGE_MESS')) {
      throw new ForbiddenError('You do not have permission to read mess complaints');
    }
    res.json({ complaint: await complaints.getComplaint(req.params.id, viewer) });
  }),
);
messRouter.post(
  '/complaints/:id/replies',
  authenticate,
  asyncHandler(async (req: Request, res: Response) => {
    const viewer = { userId: req.user!.sub, role: req.user!.role };
    if (viewer.role !== Role.STUDENT && !req.user!.perms?.includes('MANAGE_MESS')) {
      throw new ForbiddenError('You do not have permission to reply to mess complaints');
    }
    const { body } = replySchema.parse(req.body);
    res.status(201).json({ complaint: await complaints.reply(req.params.id, viewer, body) });
  }),
);
messRouter.patch(
  '/complaints/:id/status',
  authenticate,
  requirePermission('MANAGE_MESS'),
  asyncHandler(async (req: Request, res: Response) =>
    res.json({ complaint: await complaints.setStatus(req.params.id, statusSchema.parse(req.body).status) }),
  ),
);
