import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/utils";
import { renderToBuffer } from "@react-pdf/renderer";
import { InvoicePdf, InvoicePdfData } from "@/lib/pdf/invoice-pdf";
import React from "react";

async function getOrg(userId: string) {
  const m = await prisma.organizationMember.findFirst({
    where: { userId, joinedAt: { not: null } },
    include: { organization: true },
    orderBy: { createdAt: "asc" },
  });
  return m?.organization ?? null;
}

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié ou organisation introuvable" }, { status: 401 });
  const { userId, orgId } = ctx;

  const org = await getOrg(userId);
  if (!org) return NextResponse.json({ success: false, error: "Organisation introuvable" }, { status: 404 });

  const { id } = await params;
  const quote = await prisma.quote.findFirst({
    where: { id, organizationId: org.id },
    include: { customer: true, items: { orderBy: { order: "asc" } } },
  });
  if (!quote) return NextResponse.json({ success: false, error: "Devis introuvable" }, { status: 404 });

  const data: InvoicePdfData = {
    type: "DEVIS",
    number: quote.number,
    status: quote.status,
    issueDate: formatDate(quote.issueDate),
    validUntil: quote.expiryDate ? formatDate(quote.expiryDate) : null,
    reference: quote.reference,
    notes: quote.notes,
    terms: quote.terms,
    currency: quote.currency,
    seller: {
      name: org.name,
      email: org.email,
      phone: org.phone,
      address: org.address,
      city: org.city,
      postalCode: org.postalCode,
      country: org.country,
      vatNumber: org.vatNumber,
      siret: org.siret,
    },
    customer: quote.customer
      ? {
          name: quote.customer.name,
          email: quote.customer.email,
          phone: quote.customer.phone,
          address: quote.customer.address,
          city: quote.customer.city,
          postalCode: quote.customer.postalCode,
          country: quote.customer.country,
          vatNumber: quote.customer.vatNumber,
        }
      : null,
    items: quote.items.map((item) => ({
      description: item.description,
      quantity: Number(item.quantity),
      unitPrice: Number(item.unitPrice),
      taxRate: Number(item.taxRate),
      total: Number(item.total),
    })),
    subtotal: Number(quote.subtotal),
    taxAmount: Number(quote.taxAmount),
    discountAmount: Number(quote.discountAmount),
    total: Number(quote.total),
  };

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const buffer = await renderToBuffer(React.createElement(InvoicePdf, { data }) as any);

  return new NextResponse(new Uint8Array(buffer), {
    status: 200,
    headers: {
      "Content-Type": "application/pdf",
      "Content-Disposition": `attachment; filename="devis-${quote.number}.pdf"`,
      "Cache-Control": "no-store",
    },
  });
}
