import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { StayStatus } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { propertyContext } from '../../middleware/propertyContext';
import { requirePermission } from '../../middleware/requirePermission';
import { getPagination } from '../../lib/pagination';
import * as svc from './stays.service';
import { groupCheckIn, groupCheckInSchema } from './stays-group';
import { ForbiddenError } from '../../lib/errors';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import * as notify from '../notifications/notifications.service';

/** /api/stays — dormitory check-in and check-out. MANAGE_STUDENTS. */
export const stayRouter = Router();
stayRouter.use(authenticate, propertyContext, requirePermission('MANAGE_STUDENTS'));

const createSchema = z.object({
  studentProfileId: z.string().uuid(),
  bedId: z.string().uuid(),
  checkIn: z.string().datetime(),
  checkOut: z.string().datetime(),
  note: z.string().trim().max(300).optional(),
  // A charge of the office's own instead of nights × rate (hourly use, a deal).
  amount: z.number().int().min(0).max(10_000_000).optional(),
});
const stampSchema = z.object({ at: z.string().datetime().optional() });

/** `?roomIds=a,b,c`: the rooms a bed map has on screen. Absent means every room, as before. */
function roomIdsOf(raw: string | undefined): string[] | undefined {
  if (raw === undefined) return undefined;
  const ids = raw.split(',').map((s) => s.trim()).filter(Boolean);
  return z.array(z.string().uuid()).max(svc.ROOM_STAYS_ROOMS_MAX, `At most ${svc.ROOM_STAYS_ROOMS_MAX} rooms at a time`).parse(ids);
}

stayRouter.get(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const status = typeof req.query.status === 'string' && req.query.status in StayStatus ? (req.query.status as StayStatus) : undefined;
    const pagination = getPagination(req.query);
    const str = (k: string) => (typeof req.query[k] === 'string' ? (req.query[k] as string) : undefined);
    const day = (k: string) => { const v = str(k); return v && /^\d{4}-\d{2}-\d{2}$/.test(v) ? v : undefined; };
    const result = await svc.listStays(
      { status, open: req.query.open === 'true', propertyId: req.propertyId, studentProfileId: str('studentProfileId'), q: str('q')?.slice(0, 80), from: day('from'), to: day('to'), roomIds: roomIdsOf(str('roomIds')) },
      pagination,
    );
    res.json(pagination ? result : { stays: result });
  }),
);
stayRouter.get(
  '/board',
  asyncHandler(async (req: Request, res: Response) => {
    const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).parse(String(req.query.date ?? new Date().toISOString().slice(0, 10)));
    res.json({ board: await svc.dayBoard(date, req.propertyId) });
  }),
);
// Which beds are free for a whole window — planning a booking.
stayRouter.get(
  '/availability',
  asyncHandler(async (req: Request, res: Response) => {
    const q = z.object({ from: z.string().datetime(), to: z.string().datetime(), detail: z.enum(['true', 'false']).optional() }).parse(req.query);
    res.json({ availability: await svc.availabilityFor(new Date(q.from), new Date(q.to), req.propertyId, q.detail === 'true') });
  }),
);
// Who holds which bed on a day — the bed map's date picker.
stayRouter.get(
  '/occupancy',
  asyncHandler(async (req: Request, res: Response) => {
    const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).parse(String(req.query.date ?? new Date().toISOString().slice(0, 10)));
    res.json({ occupancy: await svc.occupancyOn(date, req.propertyId) });
  }),
);
stayRouter.post(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const input = createSchema.parse(req.body);
    res.status(201).json({ stay: await svc.createStay({ ...input, checkIn: new Date(input.checkIn), checkOut: new Date(input.checkOut) }, req.user!.sub) });
  }),
);
// Several walk-ins at once (27 Oct 2026): one window, one bed each, one payment.
stayRouter.post(
  '/group',
  asyncHandler(async (req: Request, res: Response) => {
    const input = groupCheckInSchema.parse(req.body);
    // Taking money is Rent & Invoices' permission, as on a single check-in.
    if (input.payment && !req.user!.perms.includes('MANAGE_RENT')) throw new ForbiddenError('Recording the payment needs the Manage rent permission');
    const result = await groupCheckIn(input, req.user!.sub, req.propertyId);
    res.status(201).json(result);
    const tenantId = getTenantIdOrThrow();
    for (const id of result.paymentIds) notify.inBackground('payment received', () => notify.notifyPaymentRecorded(tenantId, id));
  }),
);
stayRouter.post(
  '/:id/check-in',
  asyncHandler(async (req: Request, res: Response) => {
    const input = stampSchema.extend({ early: z.boolean().optional() }).parse(req.body ?? {});
    res.json({ stay: await svc.checkIn(req.params.id, { at: input.at ? new Date(input.at) : undefined, early: input.early }) });
  }),
);
stayRouter.post(
  '/:id/check-out',
  asyncHandler(async (req: Request, res: Response) => {
    const input = stampSchema.extend({ late: z.boolean().optional() }).parse(req.body ?? {});
    res.json({ stay: await svc.checkOut(req.params.id, { at: input.at ? new Date(input.at) : undefined, late: input.late }) });
  }),
);
// Reschedule or edit a booking.
stayRouter.patch(
  '/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const input = z
      .object({
        bedId: z.string().uuid().optional(),
        checkIn: z.string().datetime().optional(),
        checkOut: z.string().datetime().optional(),
        // null: back to nights × rate.
        amount: z.number().int().min(0).max(10_000_000).nullable().optional(),
        note: z.string().trim().max(300).nullable().optional(),
      })
      .parse(req.body ?? {});
    res.json({ stay: await svc.updateStay(req.params.id, { ...input, checkIn: input.checkIn ? new Date(input.checkIn) : undefined, checkOut: input.checkOut ? new Date(input.checkOut) : undefined }) });
  }),
);
stayRouter.post('/:id/cancel', asyncHandler(async (req: Request, res: Response) => res.json({ stay: await svc.cancelStay(req.params.id) })));
