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

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;
}

function round2(n: number): number {
  return Math.round(n * 100) / 100;
}

// ─── POST /api/invoices/[id]/payment ──────────────────────────

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 invoice = await prisma.invoice.findFirst({
    where: { id, organizationId },
  });

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

  if (invoice.status === "PAID") {
    return NextResponse.json(
      { success: false, error: "Cette facture est déjà entièrement payée" },
      { status: 409 }
    );
  }

  if (invoice.status === "CANCELED" || invoice.status === "REFUNDED") {
    return NextResponse.json(
      { success: false, error: `Impossible d'enregistrer un paiement sur une facture ${invoice.status}` },
      { status: 409 }
    );
  }

  const body = await request.json().catch(() => null);
  if (!body) {
    return NextResponse.json({ success: false, error: "Corps de requête invalide" }, { status: 400 });
  }

  const parsed = recordPaymentSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { success: false, error: "Données invalides", details: parsed.error.flatten() },
      { status: 422 }
    );
  }

  const { amount, method, reference, paidAt, notes } = parsed.data;

  const invoiceTotal = Number(invoice.total);
  const currentAmountPaid = Number(invoice.amountPaid);
  const newAmountPaid = round2(currentAmountPaid + amount);
  const newAmountDue = round2(Math.max(0, invoiceTotal - newAmountPaid));
  const isPaid = newAmountPaid >= invoiceTotal;

  const result = await prisma.$transaction(async (tx) => {
    const payment = await tx.invoicePayment.create({
      data: {
        invoiceId: id,
        amount,
        currency: invoice.currency,
        method,
        reference: reference ?? null,
        paidAt: paidAt ? new Date(paidAt) : new Date(),
        notes: notes ?? null,
      },
    });

    const updatedInvoice = await tx.invoice.update({
      where: { id },
      data: {
        amountPaid: newAmountPaid,
        amountDue: newAmountDue,
        ...(isPaid && {
          status: "PAID",
          paidDate: new Date(),
        }),
        // Si la facture était en DRAFT, passer à SENT lors du premier paiement
        ...(!isPaid && invoice.status === "DRAFT" && {
          status: "SENT",
        }),
      },
      include: {
        customer: { select: { id: true, name: true, email: true } },
        payments: { orderBy: { paidAt: "desc" } },
      },
    });

    return { payment, invoice: updatedInvoice };
  });

  return NextResponse.json({ success: true, data: result }, { status: 201 });
}
