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 { deviceAuth } from '../../middleware/deviceAuth';
import { propertyContext } from '../../middleware/propertyContext';
import { requireFeature, tenantHasFeature } from '../../middleware/requireFeature';
import { requirePermission } from '../../middleware/requirePermission';
import { ForbiddenError } from '../../lib/errors';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import * as svc from './canteen.service';

/**
 * /api/canteen (Sprint 5, TEPL). The canteen vendor's system posts swipes
 * with a MESS device key; employees set their diet and rate meals; the
 * kitchen (MANAGE_MESS) runs the windows, diet menus and the numbers.
 */
export const canteenRouter = Router();

const hhmm = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'time must be HH:MM');
const ymd = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'date must be YYYY-MM-DD');
const todayIst = () => new Date(Date.now() + 330 * 60_000).toISOString().slice(0, 10);

// The vendor's counter system.
canteenRouter.post('/swipes', deviceAuth, asyncHandler(async (req: Request, res: Response) => {
  if (req.device!.purpose !== 'MESS') throw new ForbiddenError('Only a mess device can send canteen swipes');
  if (!(await tenantHasFeature(req.device!.tenantId, 'canteen'))) throw new ForbiddenError('The canteen module is not switched on for this account', 'FEATURE_OFF');
  const { swipes } = z.object({ swipes: z.array(z.object({ id: z.string().trim().min(1).max(64), at: z.string().min(10).max(40), meal: z.enum(svc.MEALS).nullable().optional() })).min(1).max(5000) }).parse(req.body);
  res.status(201).json(await svc.ingestVendorSwipes(req.device!, swipes));
}));

canteenRouter.use(authenticate, requireFeature('canteen'));

// The employee.
const dietBody = z.object({ preference: z.enum(svc.PREFERENCES), restrictions: z.array(z.enum(svc.RESTRICTIONS)).max(6).default([]), allergies: z.string().trim().max(200).nullable().optional(), note: z.string().trim().max(200).nullable().optional() });
canteenRouter.get('/me/today', authorize(Role.STUDENT), asyncHandler(async (req: Request, res: Response) => res.json(await svc.myToday(req.user!.sub, ymd.optional().parse(req.query.date)))));
canteenRouter.get('/me/diet', authorize(Role.STUDENT), asyncHandler(async (req: Request, res: Response) => res.json({ diet: await svc.myDiet(req.user!.sub) })));
canteenRouter.put('/me/diet', authorize(Role.STUDENT), asyncHandler(async (req: Request, res: Response) => res.json({ diet: await svc.saveMyDiet(req.user!.sub, dietBody.parse(req.body)) })));
canteenRouter.post('/me/ratings', authorize(Role.STUDENT), asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ date: ymd, meal: z.enum(svc.MEALS), rating: z.number().int().min(1).max(5), comment: z.string().trim().max(300).nullable().optional() }).parse(req.body);
  res.json({ rating: await svc.rateMeal(req.user!.sub, input) });
}));

// The kitchen.
canteenRouter.use(propertyContext, requirePermission('MANAGE_MESS'));
canteenRouter.get('/windows', asyncHandler(async (req: Request, res: Response) => res.json({ windows: await svc.windowsFor(getTenantIdOrThrow(), req.propertyId), defaults: svc.DEFAULT_WINDOWS })));
canteenRouter.put('/windows', asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ propertyId: z.string().uuid().nullable().optional(), windows: z.array(z.object({ meal: z.enum(svc.MEALS), startTime: hhmm, endTime: hhmm })).min(1).max(4) }).parse(req.body);
  res.json({ windows: await svc.saveWindows(input.propertyId ?? null, input.windows) });
}));
canteenRouter.get('/diets', asyncHandler(async (req: Request, res: Response) => res.json(await svc.dietSummary(req.propertyId))));
canteenRouter.get('/diet-menus', asyncHandler(async (_req: Request, res: Response) => res.json({ menus: await svc.dietMenus() })));
canteenRouter.put('/diet-menus', asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ dayOfWeek: z.number().int().min(0).max(6), meal: z.enum(svc.MEALS), diet: z.enum([...svc.PREFERENCES, ...svc.RESTRICTIONS]), items: z.string().trim().max(500).nullable() }).parse(req.body);
  res.json({ menu: await svc.saveDietMenu(input) });
}));
canteenRouter.get('/today', asyncHandler(async (req: Request, res: Response) => res.json(await svc.today(req.propertyId))));
canteenRouter.get('/consumption', asyncHandler(async (req: Request, res: Response) => {
  const q = z.object({ from: ymd.optional(), to: ymd.optional() }).parse(req.query);
  const to = q.to ?? todayIst();
  res.json(await svc.consumption(q.from ?? new Date(Date.parse(`${to}T00:00:00.000Z`) - 6 * 86_400_000).toISOString().slice(0, 10), to, req.propertyId));
}));
canteenRouter.get('/ratings', asyncHandler(async (req: Request, res: Response) => res.json(await svc.ratingSummary(z.coerce.number().int().min(1).max(92).default(30).parse(req.query.days ?? 30), req.propertyId))));
