import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { createInvoiceSchema } from "@/lib/validations/invoice";
import { generateInvoiceNumber } from "@/lib/utils";
import { InvoiceStatus, Prisma } from "@prisma/client";

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

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

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

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

// ─── GET /api/invoices ────────────────────────────────────────

export async function GET(request: NextRequest) {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });
  const { userId, orgId } = ctx;

  const { searchParams } = new URL(request.url);
  const page = Math.max(1, parseInt(searchParams.get("page") ?? "1", 10));
  const limit = Math.min(100, Math.max(1, parseInt(searchParams.get("limit") ?? "20", 10)));
  const status = searchParams.get("status") as InvoiceStatus | null;
  const search = searchParams.get("search")?.trim() ?? "";

  const where: Prisma.InvoiceWhereInput = {
    organizationId: orgId,
    ...(status && { status }),
    ...(search && {
      OR: [
        { number: { contains: search, mode: "insensitive" } },
        { customer: { name: { contains: search, mode: "insensitive" } } },
        { reference: { contains: search, mode: "insensitive" } },
      ],
    }),
  };

  const [invoices, total] = await prisma.$transaction([
    prisma.invoice.findMany({
      where,
      include: {
        customer: { select: { id: true, name: true, email: true } },
        _count: { select: { items: true, payments: true } },
      },
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * limit,
      take: limit,
    }),
    prisma.invoice.count({ where }),
  ]);

  return NextResponse.json({
    success: true,
    data: invoices,
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit),
    },
  });
}

// ─── POST /api/invoices ───────────────────────────────────────

export async function POST(request: NextRequest) {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });
  const { userId, orgId } = ctx;

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

  const parsed = createInvoiceSchema.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 que le client appartient à l'organisation si fourni
  if (data.customerId) {
    const customer = await prisma.customer.findFirst({
      where: { id: data.customerId, organizationId: orgId },
    });
    if (!customer) {
      return NextResponse.json(
        { success: false, error: "Client introuvable dans cette organisation" },
        { status: 404 }
      );
    }
  }

  // Calcul des totaux par ligne et agrégats
  let subtotal = 0;
  let totalTaxAmount = 0;
  let totalDiscountAmount = 0;

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

  subtotal = round2(subtotal);
  totalTaxAmount = round2(totalTaxAmount);
  totalDiscountAmount = round2(totalDiscountAmount);
  const invoiceTotal = round2(subtotal + totalTaxAmount);

  // Génération du numéro et incrémentation du compteur (transaction atomique)
  const invoice = await prisma.$transaction(async (tx) => {
    const freshOrg = await tx.organization.findUniqueOrThrow({
      where: { id: orgId },
      select: { invoicePrefix: true, invoiceCounter: true },
    });

    const number = generateInvoiceNumber(freshOrg.invoicePrefix, freshOrg.invoiceCounter);

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

    return tx.invoice.create({
      data: {
        organizationId: orgId,
        customerId: data.customerId ?? null,
        number,
        status: "DRAFT",
        issueDate: data.issueDate ? new Date(data.issueDate) : new Date(),
        dueDate: data.dueDate ? new Date(data.dueDate) : null,
        currency: data.currency,
        notes: data.notes ?? null,
        terms: data.terms ?? null,
        subtotal,
        taxAmount: totalTaxAmount,
        discountAmount: totalDiscountAmount,
        total: invoiceTotal,
        amountPaid: 0,
        amountDue: invoiceTotal,
        items: { create: itemsData },
      },
      include: {
        customer: { select: { id: true, name: true, email: true } },
        items: true,
      },
    });
  });

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