import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { Prisma } from "@prisma/client";

// ─── Helpers ───────────────────────────────────────────────────

async function getOrganizationId(userId: string): Promise<string | null> {
  const membership = await prisma.organizationMember.findFirst({
    where: { userId, joinedAt: { not: null } },
    select: { organizationId: true },
    orderBy: { createdAt: "asc" },
  });
  return membership?.organizationId ?? null;
}

async function generateInvoiceNumber(
  tx: Prisma.TransactionClient,
  organizationId: string
): Promise<string> {
  const freshOrg = await tx.organization.findUniqueOrThrow({
    where: { id: organizationId },
    select: { invoicePrefix: true, invoiceCounter: true },
  });

  const year = new Date().getFullYear();
  const padded = String(freshOrg.invoiceCounter + 1).padStart(4, "0");
  const number = `${freshOrg.invoicePrefix}-${year}-${padded}`;

  await tx.organization.update({
    where: { id: organizationId },
    data: { invoiceCounter: { increment: 1 } },
  });

  return number;
}

// ─── POST /api/quotes/[id]/convert ────────────────────────────

export async function POST(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });
  const { userId, orgId } = ctx;
  const organizationId = await getOrganizationId(userId);
  if (!organizationId) {
    return NextResponse.json({ success: false, error: "Aucune organisation trouvée" }, { status: 404 });
  }

  const { id } = await params;

  const quote = await prisma.quote.findFirst({
    where: { id, organizationId },
    include: {
      items: { orderBy: { order: "asc" } },
    },
  });

  if (!quote) {
    return NextResponse.json({ success: false, error: "Devis introuvable" }, { status: 404 });
  }

  if (quote.status !== "ACCEPTED") {
    return NextResponse.json(
      { success: false, error: "Le devis doit être accepté avant conversion" },
      { status: 400 }
    );
  }

  const result = await prisma.$transaction(async (tx) => {
    const invoiceNumber = await generateInvoiceNumber(tx, organizationId);

    const invoice = await tx.invoice.create({
      data: {
        organizationId,
        customerId: quote.customerId ?? null,
        number: invoiceNumber,
        status: "DRAFT",
        issueDate: new Date(),
        currency: quote.currency,
        notes: quote.notes ?? null,
        terms: quote.terms ?? null,
        reference: quote.reference ?? null,
        subtotal: quote.subtotal,
        taxAmount: quote.taxAmount,
        discountAmount: quote.discountAmount,
        total: quote.total,
        amountPaid: 0,
        amountDue: quote.total,
        items: {
          create: quote.items.map((item) => ({
            description: item.description,
            quantity: item.quantity,
            unitPrice: item.unitPrice,
            taxRate: item.taxRate,
            taxAmount: item.taxAmount,
            discount: item.discount,
            total: item.total,
            order: item.order,
          })),
        },
      },
      select: { id: true, number: true },
    });

    await tx.quote.update({
      where: { id },
      data: {
        status: "CONVERTED",
        convertedAt: new Date(),
        convertedInvoiceId: invoice.id,
      },
    });

    return invoice;
  });

  return NextResponse.json({
    success: true,
    data: {
      invoiceId: result.id,
      invoiceNumber: result.number,
    },
  });
}
