import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { id, parse, route, sendFile } from "../../core/http/route.js";
import { publicStats } from "./public.service.js";
import * as s from "./reporting.service.js";

const R = "GET /api/projects/:projectId/reports";
const both = (x: string) => [`${R}/${x}.pdf`, `${R}/${x}.docx`];
export async function reportingRoutes(app: FastifyInstance): Promise<void> {
  const p = "/projects/:p";
  route(app, "GET", "/public/stats", { public: true, limit: 60, v1: ["GET /api/landing"] }, async () => publicStats());
  route(app, "GET", `${p}/dashboard/programme`, { perm: "indicator.view", v1: ["GET /api/projects/:projectId/dashboard"] }, async (c) => s.programme(c));
  route(app, "GET", `${p}/dashboard/provider/:id`, { perm: "provider.view" }, async (c) => s.provider(c, c.params["id"]!));
  route(app, "GET", `${p}/reports/catalogue`, { perm: ["report.view", "report.export"] }, async (c) => s.catalogue(c));
  route(app, "POST", `${p}/reports/:key`, { perm: ["report.export", "report.view"], v1: [...both("activities/compliance"), ...both("dashboard/claimed-verified"), `${R}/feedback/detailed.csv`, `${R}/feedback/detailed.pdf`, ...both("feedback/summary"), ...both("indicators/summary"), ...both("providers/:providerId/profile"), ...both("trainees/:traineeId/profile"), ...both("verification-runs/summary"), ...both("verification-runs/:runId(\\d+)"), "GET /api/projects/:projectId/ops/executive-pack"] }, async (c) => s.generate(c, c.params["key"]!, parse(z.object({ format: z.enum(["pdf", "docx", "xlsx", "csv"]), providerId: id.optional(), classId: id.optional(), traineeId: id.optional(), runId: id.optional(), dims: z.string().regex(/^[a-z,]{0,60}$/).optional(), period: z.string().regex(/^\d{4}-\d{2}$/).optional() }), c.body)));
  route(app, "GET", `${p}/files/:id`, {}, async (c) => { const f = await s.file(c, c.params["id"]!); return sendFile(c, f.name, f.mime, f.data); });
  route(app, "POST", `${p}/jobs`, {}, async (c) => { const b = parse(z.object({ kind: z.string(), params: z.record(z.unknown()).default({}) }), c.body); return s.startJob(c, b.kind, b.params); });
  route(app, "GET", `${p}/jobs/:id`, {}, async (c) => s.job(c, c.params["id"]!));
  route(app, "GET", `${p}/search`, {}, async (c) => s.search(c));
}
