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

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

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

function calcItemTotals(item: {
  quantity: number;
  unitPrice: number;
  discount: number;
  taxRate: number;
}) {
  const baseAmount = item.quantity * item.unitPrice * (1 - item.discount / 100);
  const taxAmount = baseAmount * (item.taxRate / 100);
  const total = baseAmount + taxAmount;
  return {
    baseAmount: round2(baseAmount),
    taxAmount: round2(taxAmount),
    total: round2(total),
  };
}

// ─── GET /api/invoices/[id] ───────────────────────────────────

export async function GET(
  _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 },
    include: {
      customer: true,
      items: { orderBy: { order: "asc" } },
      payments: { orderBy: { paidAt: "desc" } },
      documents: true,
    },
  });

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

  return NextResponse.json({ success: true, data: invoice });
}

// ─── PATCH /api/invoices/[id] ─────────────────────────────────

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

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

  if (existing.status !== "DRAFT" && existing.status !== "SENT") {
    return NextResponse.json(
      { success: false, error: "Seules les factures en brouillon ou envoyées peuvent être modifiées" },
      { 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 = updateInvoiceSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { success: false, error: "Données invalides", details: parsed.error.flatten() },
      { status: 422 }
    );
  }

  const data = parsed.data;

  // Vérifier le client si fourni
  if (data.customerId) {
    const customer = await prisma.customer.findFirst({
      where: { id: data.customerId, organizationId },
    });
    if (!customer) {
      return NextResponse.json(
        { success: false, error: "Client introuvable dans cette organisation" },
        { status: 404 }
      );
    }
  }

  // Si des items sont fournis, recalculer les totaux
  let invoiceUpdateData: Record<string, unknown> = {
    ...(data.customerId !== undefined && { customerId: data.customerId }),
    ...(data.issueDate !== undefined && { issueDate: new Date(data.issueDate) }),
    ...(data.dueDate !== undefined && { dueDate: new Date(data.dueDate) }),
    ...(data.currency !== undefined && { currency: data.currency }),
    ...(data.notes !== undefined && { notes: data.notes }),
    ...(data.terms !== undefined && { terms: data.terms }),
  };

  if (data.items && data.items.length > 0) {
    let subtotal = 0;
    let totalTaxAmount = 0;
    let totalDiscountAmount = 0;

    const itemsData = data.items.map((item, index) => {
      const discount = item.discount ?? 0;
      const { baseAmount, taxAmount, total } = calcItemTotals({
        ...item,
        discount,
      });
      const discountAmountForItem = round2(item.quantity * item.unitPrice * (discount / 100));
      subtotal += baseAmount;
      totalTaxAmount += taxAmount;
      totalDiscountAmount += discountAmountForItem;
      return {
        description: item.description,
        quantity: item.quantity,
        unitPrice: item.unitPrice,
        taxRate: item.taxRate,
        taxAmount,
        discount,
        total,
        accountCode: item.accountCode ?? null,
        order: item.order ?? index,
      };
    });

    subtotal = round2(subtotal);
    totalTaxAmount = round2(totalTaxAmount);
    totalDiscountAmount = round2(totalDiscountAmount);
    const invoiceTotal = round2(subtotal + totalTaxAmount);
    const amountPaid = Number(existing.amountPaid);
    const amountDue = round2(Math.max(0, invoiceTotal - amountPaid));

    invoiceUpdateData = {
      ...invoiceUpdateData,
      subtotal,
      taxAmount: totalTaxAmount,
      discountAmount: totalDiscountAmount,
      total: invoiceTotal,
      amountDue,
    };

    // Remplacer tous les items
    const updated = await prisma.$transaction(async (tx) => {
      await tx.invoiceItem.deleteMany({ where: { invoiceId: id } });
      return tx.invoice.update({
        where: { id },
        data: {
          ...invoiceUpdateData,
          items: { create: itemsData },
        },
        include: {
          customer: { select: { id: true, name: true, email: true } },
          items: { orderBy: { order: "asc" } },
          payments: { orderBy: { paidAt: "desc" } },
        },
      });
    });

    return NextResponse.json({ success: true, data: updated });
  }

  const updated = await prisma.invoice.update({
    where: { id },
    data: invoiceUpdateData,
    include: {
      customer: { select: { id: true, name: true, email: true } },
      items: { orderBy: { order: "asc" } },
      payments: { orderBy: { paidAt: "desc" } },
    },
  });

  return NextResponse.json({ success: true, data: updated });
}

// ─── DELETE /api/invoices/[id] ────────────────────────────────

export async function DELETE(
  _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 !== "DRAFT") {
    return NextResponse.json(
      { success: false, error: "Seules les factures en brouillon peuvent être supprimées" },
      { status: 409 }
    );
  }

  await prisma.invoice.delete({ where: { id } });

  return NextResponse.json({ success: true, data: { id } });
}
