import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { ReportFrequency } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requireFeature } from '../../middleware/requireFeature';
import { requirePermission } from '../../middleware/requirePermission';
import { propertyContext } from '../../middleware/propertyContext';
import { BadRequestError, ForbiddenError } from '../../lib/errors';
import { XLSX_MIME } from '../../lib/xlsx';
import * as svc from './reports.service';

/**
 * /api/reports — Excel downloads and scheduled report emails. Each report
 * carries its own permission (reports.registry); managing schedules needs
 * VIEW_ANALYTICS as well, since it sends hostel data to email addresses.
 */
export const reportRouter = Router();
reportRouter.use(authenticate, requireFeature('reports'));

const staffOnly = (req: Request) => {
  if (!req.user!.perms.length) throw new ForbiddenError('Reports are for staff');
};

reportRouter.get(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    staffOnly(req);
    res.json({ reports: await svc.catalogue(req.user!.perms) });
  }),
);

const scheduleSchema = z.object({
  reportKey: z.string().min(1).max(60),
  frequency: z.nativeEnum(ReportFrequency),
  hour: z.coerce.number().int().min(0).max(23),
  weekday: z.coerce.number().int().min(1).max(7).nullable().optional(),
  monthDay: z.coerce.number().int().min(1).max(28).nullable().optional(),
  recipients: z.array(z.string().trim().toLowerCase().email()).min(1).max(10),
  propertyId: z.string().uuid().nullable().optional(),
  isActive: z.boolean().optional(),
});

reportRouter.get('/schedules', requirePermission('VIEW_ANALYTICS'), asyncHandler(async (_req, res) => res.json({ schedules: await svc.listSchedules() })));
reportRouter.post(
  '/schedules',
  requirePermission('VIEW_ANALYTICS'),
  asyncHandler(async (req: Request, res: Response) => res.status(201).json({ schedule: await svc.createSchedule(scheduleSchema.parse(req.body), req.user!.perms, req.user!.sub) })),
);
reportRouter.patch(
  '/schedules/:id',
  requirePermission('VIEW_ANALYTICS'),
  asyncHandler(async (req: Request, res: Response) => res.json({ schedule: await svc.updateSchedule(req.params.id, scheduleSchema.partial().parse(req.body), req.user!.perms) })),
);
reportRouter.delete('/schedules/:id', requirePermission('VIEW_ANALYTICS'), asyncHandler(async (req, res) => res.json(await svc.deleteSchedule(req.params.id))));
reportRouter.post('/schedules/:id/send', requirePermission('VIEW_ANALYTICS'), asyncHandler(async (req, res) => res.json(await svc.sendScheduleNow(req.params.id))));

const rangeOf = (query: unknown) => {
  const q = z.object({ from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional() }).parse(query);
  return q.from && q.to ? { from: q.from, to: q.to } : undefined;
};

const pageQuery = z.object({
  page: z.coerce.number().int().min(1).max(100_000),
  limit: z.coerce.number().int().min(1).max(200).default(50),
  sheet: z.coerce.number().int().min(0).max(50).default(0),
  q: z.string().trim().max(100).optional().transform((v) => v || undefined),
  sort: z.coerce.number().int().min(0).max(200).optional(),
  dir: z.enum(['asc', 'desc']).optional(),
});

/** The report to read on screen; X-Property-Id narrows it to one property. */
reportRouter.get(
  '/:key/view',
  propertyContext,
  asyncHandler(async (req: Request, res: Response) => {
    staffOnly(req);
    // `page` sends one page of one sheet, searched and sorted here (Sprint L4); without it, every row up to 5,000 a sheet as before.
    const paged = pageQuery.safeParse(req.query);
    if (req.query.page !== undefined) {
      if (!paged.success) throw new BadRequestError('page, limit (1 to 200), sheet, sort or dir is not valid');
      const { sheet, page, limit, q, sort, dir } = paged.data;
      res.json({ report: await svc.viewReportPage(req.params.key, req.user!.perms, req.propertyId, new Date(), rangeOf(req.query), { sheet, page, limit, q, sort: sort === undefined ? undefined : { col: sort, dir: dir === 'desc' ? -1 : 1 } }) });
      return;
    }
    res.json({ report: await svc.viewReport(req.params.key, req.user!.perms, req.propertyId, new Date(), rangeOf(req.query)) });
  }),
);

/** The report as an .xlsx; X-Property-Id narrows it to one property. */
reportRouter.get(
  '/:key/download',
  propertyContext,
  asyncHandler(async (req: Request, res: Response) => {
    staffOnly(req);
    const range = rangeOf(req.query);
    const report = await svc.buildReport(req.params.key, req.user!.perms, req.propertyId, new Date(), range);
    res.setHeader('Content-Type', XLSX_MIME);
    // A property name can carry any character: an ASCII fallback, and the real name encoded (RFC 6266).
    const ascii = report.filename.replace(/[^\x20-\x7e]/g, '_').replace(/"/g, '');
    res.setHeader('Content-Disposition', `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(report.filename)}`);
    res.send(report.bytes);
  }),
);
