import { TRPCError } from "@trpc/server";
import { generateMaterialEventPDF, generateReservationPDF } from "./pdfGenerator";

type RequestLike = {
  id: number;
  type: string;
  titre: string;
  status: string;
  createdAt: Date | string;
  dateSubmission?: Date | string | null;
  dateTraitement?: Date | string | null;
  commentaireAdmin?: string | null;
  formData?: string | null;
};

export async function generateRequestPdfDocument(request: RequestLike) {
  let formData: any = {};
  try {
    formData = request.formData ? JSON.parse(request.formData) : {};
  } catch {
    formData = {};
  }

  if (request.type === "demande_salle") {
    const pdfBuffer = await generateReservationPDF({
      titre: request.titre,
      status: request.status,
      createdAt: request.createdAt,
      dateSubmission: request.dateSubmission,
      dateTraitement: request.dateTraitement,
      commentaireAdmin: request.commentaireAdmin,
      formData,
    });

    return {
      buffer: pdfBuffer,
      storageName: `reservations/pdf-${request.id}-${Date.now()}.pdf`,
      fileName: `Reservation_${request.id}_${formData.nomAssociation || "association"}.pdf`,
      contentType: "application/pdf",
    };
  }

  if (request.type === "demande_materiel_evenementiel") {
    const pdfBuffer = await generateMaterialEventPDF({
      titre: request.titre,
      status: request.status,
      createdAt: request.createdAt,
      dateSubmission: request.dateSubmission,
      dateTraitement: request.dateTraitement,
      commentaireAdmin: request.commentaireAdmin,
      formData,
    });

    return {
      buffer: pdfBuffer,
      storageName: `materiel-evenementiel/pdf-${request.id}-${Date.now()}.pdf`,
      fileName: `Materiel_Evenementiel_${request.id}_${formData.nomAssociation || formData.commune || "association"}.pdf`,
      contentType: "application/pdf",
    };
  }

  throw new TRPCError({
    code: "BAD_REQUEST",
    message: "Le PDF n'est disponible que pour les demandes de salle et de matériel événementiel",
  });
}
