import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import path from "path";

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const folderId = parseInt(searchParams.get("folderId") || "");
  const selectedInvoiceId = searchParams.get("selectedInvoiceId");

  if (!folderId) {
    return NextResponse.json({ error: "Missing folderId" }, { status: 400 });
  }

  try {
    const [communications, invoices, activityLogs] = await Promise.all([
      prisma.communication.findMany({
        where: { folderId },
        include: { client: true, folder: true },
      }),
      prisma.invoice.findMany({
        where: { folderId },
        include: { client: true, folder: true },
        orderBy: { issueDate: "desc" },
      }),
      prisma.activityLog.findMany({
        where: { folderId },
        include: {
          client: true,
          communication: true,
          partner: true,
          task: true,
        },
        orderBy: { createdAt: "desc" },
      }),
    ]);

    // Normalisation des factures
    const openInvoices = invoices
      .filter(inv => inv.status === "OPEN")
      .map(inv => ({
        id: `inv-${inv.id}`,
        type: "invoice",
        invoiceType: "open",
        title: inv.description || `Facture ouverte`,
        invoiceNumber: inv.invoiceNumber,
        invoiceDate: inv.issueDate,
        dueDate: inv.dueDate,
        amount: inv.amount,
        client: inv.client,
        status: inv.status,
        pdfUrl: null, // Le modèle Invoice n'a pas de pdfPath
        isSelected: selectedInvoiceId === String(inv.id),
      }));

    const paidInvoices = invoices
      .filter(inv => inv.status === "PAID")
      .map(inv => ({
        id: `inv-${inv.id}`,
        type: "invoice",
        invoiceType: "paid",
        title: inv.description || `Facture réglée`,
        invoiceNumber: inv.invoiceNumber,
        invoiceDate: inv.issueDate,
        amount: inv.amount,
        client: inv.client,
        status: inv.status,
        pdfUrl: null, // Le modèle Invoice n'a pas de pdfPath
        isSelected: selectedInvoiceId === String(inv.id),
      }));

    // Communications
    const formattedComms = communications.map(comm => ({
      id: `comm-${comm.id}`,
      type: "communication",
      title: comm.subject || 'Communication',
      summary: comm.content,
      date: comm.createdAt,
      client: comm.client,
    }));

    // Logs d'activité génériques
    const formattedLogs = activityLogs.map(log => ({
      id: `log-${log.id}`,
      type: "log",
      title: log.action,
      summary: log.description || '',
      date: log.createdAt,
      client: log.client,
      communication: log.communication,
      partner: log.partner,
      task: log.task,
    }));

    // Fusionner tous les éléments pour affichage général (Journal complet)
    const journalEntries = [...formattedComms, ...openInvoices, ...paidInvoices, ...formattedLogs];
    journalEntries.sort((a, b) => {
      const dateA = 'invoiceDate' in a ? a.invoiceDate : a.date;
      const dateB = 'invoiceDate' in b ? b.invoiceDate : b.date;
      return new Date(dateB).getTime() - new Date(dateA).getTime();
    });

    return NextResponse.json({
      invoices: {
        open: openInvoices,
        paid: paidInvoices,
      },
      communications: formattedComms,
      activityLogs: formattedLogs,
      journal: journalEntries,
    });
  } catch (error) {
    console.error("Error fetching journal:", error);
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}
