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

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

async function getOrgId(userId: string) {
}

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

function calcNextRunDate(from: Date, frequency: RecurringFrequency): Date {
  const d = new Date(from);
  switch (frequency) {
    case "WEEKLY":    d.setDate(d.getDate() + 7); break;
    case "MONTHLY":   d.setMonth(d.getMonth() + 1); break;
    case "QUARTERLY": d.setMonth(d.getMonth() + 3); break;
    case "YEARLY":    d.setFullYear(d.getFullYear() + 1); break;
  }
  return d;
}

// ─── Schemas ───────────────────────────────────────────────────

const itemSchema = z.object({
  description: z.string().min(1, "Description requise"),
  quantity: z.coerce.number().positive(),
  unitPrice: z.coerce.number().min(0),
  taxRate: z.coerce.number().min(0).max(100).default(0),
  discount: z.coerce.number().min(0).max(100).default(0),
  order: z.number().int().default(0),
});

const createSchema = z.object({
  customerId: z.string().optional(),
  subject: z.string().optional(),
  frequency: z.enum(["WEEKLY", "MONTHLY", "QUARTERLY", "YEARLY"]),
  startDate: z.string(),
  endDate: z.string().optional(),
  currency: z.string().default("XOF"),
  notes: z.string().optional(),
  terms: z.string().optional(),
  reference: z.string().optional(),
  items: z.array(itemSchema).min(1, "Au moins un article requis"),
});

// ─── GET /api/recurring-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;
  if (!orgId) return NextResponse.json({ success: false, error: "Organisation introuvable" }, { status: 404 });

  const { searchParams } = new URL(request.url);
  const status = searchParams.get("status") ?? undefined;
  const page = Math.max(1, parseInt(searchParams.get("page") ?? "1"));
  const limit = Math.min(100, Math.max(1, parseInt(searchParams.get("limit") ?? "20")));

  const where: Prisma.RecurringInvoiceWhereInput = {
    organizationId: orgId,
    ...(status && { status: status as any }),
  };

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

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

// ─── POST /api/recurring-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;
  if (!orgId) return NextResponse.json({ success: false, error: "Organisation introuvable" }, { status: 404 });

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

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

  const data = parsed.data;

  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" }, { status: 404 });
  }

  let subtotal = 0, totalTax = 0, totalDiscount = 0;
  const itemsData = data.items.map((item, index) => {
    const disc = item.discount ?? 0;
    const base = round2(item.quantity * item.unitPrice * (1 - disc / 100));
    const tax = round2(base * (item.taxRate / 100));
    const discAmt = round2(item.quantity * item.unitPrice * (disc / 100));
    subtotal += base;
    totalTax += tax;
    totalDiscount += discAmt;
    return {
      description: item.description,
      quantity: item.quantity,
      unitPrice: item.unitPrice,
      taxRate: item.taxRate,
      taxAmount: tax,
      discount: disc,
      total: round2(base + tax),
      order: item.order ?? index,
    };
  });

  subtotal = round2(subtotal);
  totalTax = round2(totalTax);
  totalDiscount = round2(totalDiscount);
  const startDate = new Date(data.startDate);

  const recurring = await prisma.recurringInvoice.create({
    data: {
      organizationId: orgId,
      customerId: data.customerId ?? null,
      frequency: data.frequency,
      status: "ACTIVE",
      startDate,
      endDate: data.endDate ? new Date(data.endDate) : null,
      nextRunDate: startDate,
      currency: data.currency,
      subject: data.subject ?? null,
      notes: data.notes ?? null,
      terms: data.terms ?? null,
      reference: data.reference ?? null,
      subtotal,
      taxAmount: totalTax,
      discountAmount: totalDiscount,
      total: round2(subtotal + totalTax),
      items: { create: itemsData },
    },
    include: {
      customer: { select: { id: true, name: true, email: true } },
      items: { orderBy: { order: "asc" } },
    },
  });

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