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

async function getOrgId(userId: string) {
  const m = await prisma.organizationMember.findFirst({
    where: { userId, joinedAt: { not: null } },
    select: { organizationId: true, organization: true },
  });
  return m ?? null;
}

// POST /api/interventions/[id]/invoice
// Crée une facture depuis un bon d'intervention terminé
export async function POST(
  _req: 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 membership = await getOrgId(userId);
  if (!membership) return NextResponse.json({ success: false, error: "Organisation introuvable" }, { status: 404 });

  const { id } = await params;
  const intervention = await prisma.interventionOrder.findFirst({
    where: { id, organizationId: membership.organizationId },
  });

  if (!intervention) return NextResponse.json({ success: false, error: "Bon introuvable" }, { status: 404 });
  if (intervention.status !== "DONE") return NextResponse.json({ success: false, error: "L'intervention doit être terminée pour créer une facture" }, { status: 400 });
  if (intervention.invoiceId) return NextResponse.json({ success: false, error: "Une facture existe déjà pour cette intervention" }, { status: 409 });

  const org = membership.organization;

  // Incrémenter le compteur et générer le numéro de facture
  const updatedOrg = await prisma.organization.update({
    where: { id: orgId },
    data: { invoiceCounter: { increment: 1 } },
    select: { invoiceCounter: true, invoicePrefix: true },
  });
  const invoiceNumber = `${updatedOrg.invoicePrefix}-${String(updatedOrg.invoiceCounter).padStart(4, "0")}`;

  // Construire les lignes à partir de la prestation + matériaux
  type Material = { name: string; quantity: number; unitPrice: number };
  const materials = (intervention.materials ?? []) as Material[];
  const items: { description: string; quantity: number; unitPrice: number; taxRate: number; taxAmount: number; discount: number; total: number; order: number }[] = [];

  // Ligne prestation principale
  const durationHours = intervention.duration ? intervention.duration / 60 : 1;
  items.push({
    description: intervention.title,
    quantity: durationHours,
    unitPrice: 0, // à renseigner manuellement sur la facture
    taxRate: 0,
    taxAmount: 0,
    discount: 0,
    total: 0,
    order: 0,
  });

  // Lignes matériaux
  materials.forEach((m, i) => {
    const ht = m.quantity * m.unitPrice;
    items.push({
      description: m.name,
      quantity: m.quantity,
      unitPrice: m.unitPrice,
      taxRate: 0,
      taxAmount: 0,
      discount: 0,
      total: ht,
      order: i + 1,
    });
  });

  // Créer la facture
  const invoice = await prisma.invoice.create({
    data: {
      organizationId: orgId,
      customerId: intervention.customerId ?? undefined,
      number: invoiceNumber,
      currency: org.currency ?? "XOF",
      notes: `Bon d'intervention n° ${intervention.number}${intervention.resolution ? `\n\nRésolution : ${intervention.resolution}` : ""}`,
      items: { create: items },
    },
  });

  // Lier le bon à la facture
  await prisma.interventionOrder.update({
    where: { id: intervention.id },
    data: { invoiceId: invoice.id },
  });

  return NextResponse.json({ success: true, data: { invoiceId: invoice.id, invoiceNumber } }, { status: 201 });
}
