import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = await params;
  const rawId = resolvedParams.id;

  try {
    if (rawId.startsWith("comm-")) {
      const id = parseInt(rawId.replace("comm-", ""));
      const comm = await prisma.communication.findUnique({
        where: { id },
        // include: { partner: true }, // supprimé car non existant
      });
      if (!comm) return NextResponse.json({ error: "Not found" }, { status: 404 });
      return NextResponse.json({ entryType: "communication", ...comm });
    }

    if (rawId.startsWith("inv-")) {
      const id = parseInt(rawId.replace("inv-", ""));
      const invoice = await prisma.invoice.findUnique({
        where: { id },
        include: {
          client: true, // inclut le client lié
          InvoiceComment: {
            include: {
              user: true,
            },
          },
        },
      });
      if (!invoice) return NextResponse.json({ error: "Not found" }, { status: 404 });
      return NextResponse.json({ entryType: "invoice", ...invoice });
    }

    return NextResponse.json({ error: "Invalid ID" }, { status: 400 });
  } catch (error) {
    console.error("Error fetching journal entry:", error);
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}
