import { Injectable, NotFoundException } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { findReport, REPORTS } from "./reports.registry";
import type { ReportDef } from "./reports.types";

/**
 * The reports service. Two responsibilities:
 *  1. Run a report by slug with the given params — just dispatch.
 *  2. Return the catalog for the /reportes index page.
 *
 * Output rendering (CSV/XLSX/PDF/HTML print) lives in `outputs.ts`; this
 * service is data only. The controller maps URLs to (slug, format) and
 * hands the result to outputs.
 */
@Injectable()
export class ReportsService {
  constructor(private readonly prisma: PrismaService) {}

  /** List every registered report, in display order. */
  catalog(): Array<{
    slug: string;
    title: string;
    description: string;
    domain: string;
    legacyName: string | null;
    format: string;
    params: ReportDef["params"];
  }> {
    return REPORTS.map((r) => ({
      slug: r.slug,
      title: r.title,
      description: r.description,
      domain: r.domain,
      legacyName: r.legacyName,
      format: r.format,
      params: r.params,
    }));
  }

  async run(slug: string, params: Record<string, string | undefined>) {
    const def = findReport(slug);
    if (!def) throw new NotFoundException(`Reporte "${slug}" no encontrado`);
    return def.run(this.prisma, params);
  }
}
