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

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

async function getOrgId(userId: string) {
}

async function generateNumber(tx: Prisma.TransactionClient, orgId: string) {
  const year = new Date().getFullYear();
  const prefix = `BL-${year}-`;
  const last = await tx.deliveryNote.findFirst({
    where: { organizationId: orgId, number: { startsWith: prefix } },
    orderBy: { number: "desc" },
    select: { number: true },
  });
  let counter = 1;
  if (last?.number) {
    const parts = last.number.split("-");
    const n = parseInt(parts[parts.length - 1] ?? "0", 10);
    if (!isNaN(n)) counter = n + 1;
  }
  return `${prefix}${String(counter).padStart(4, "0")}`;
}

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

const itemSchema = z.object({
  description: z.string().min(1, "Description requise"),
  orderedQty: z.coerce.number().min(0),
  deliveredQty: z.coerce.number().min(0),
  unit: z.string().optional(),
  notes: z.string().optional(),
  order: z.number().int().default(0),
});

const createSchema = z.object({
  customerId: z.string().optional(),
  invoiceId: z.string().optional(),
  issueDate: z.string(),
  deliveryDate: z.string().optional(),
  shippingAddress: z.string().optional(),
  notes: z.string().optional(),
  reference: z.string().optional(),
  items: z.array(itemSchema).min(1, "Au moins un article requis"),
});

// ─── GET /api/delivery-notes ───────────────────────────────────

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 search = searchParams.get("search")?.trim() ?? "";
  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.DeliveryNoteWhereInput = {
    organizationId: orgId,
    ...(status && { status: status as any }),
    ...(search && {
      OR: [
        { number: { contains: search, mode: "insensitive" } },
        { reference: { contains: search, mode: "insensitive" } },
        { customer: { name: { contains: search, mode: "insensitive" } } },
      ],
    }),
  };

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

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

// ─── POST /api/delivery-notes ──────────────────────────────────

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;

  // Vérifier client et facture si fournis
  if (data.customerId) {
    const c = await prisma.customer.findFirst({ where: { id: data.customerId, organizationId: orgId } });
    if (!c) return NextResponse.json({ success: false, error: "Client introuvable" }, { status: 404 });
  }
  if (data.invoiceId) {
    const inv = await prisma.invoice.findFirst({ where: { id: data.invoiceId, organizationId: orgId } });
    if (!inv) return NextResponse.json({ success: false, error: "Facture introuvable" }, { status: 404 });
  }

  const note = await prisma.$transaction(async (tx) => {
    const number = await generateNumber(tx, orgId);
    return tx.deliveryNote.create({
      data: {
        organizationId: orgId,
        customerId: data.customerId ?? null,
        invoiceId: data.invoiceId ?? null,
        number,
        status: "DRAFT",
        issueDate: new Date(data.issueDate),
        deliveryDate: data.deliveryDate ? new Date(data.deliveryDate) : null,
        shippingAddress: data.shippingAddress ?? null,
        notes: data.notes ?? null,
        reference: data.reference ?? null,
        items: {
          create: data.items.map((item, i) => ({
            description: item.description,
            orderedQty: item.orderedQty,
            deliveredQty: item.deliveredQty,
            unit: item.unit ?? null,
            notes: item.notes ?? null,
            order: item.order ?? i,
          })),
        },
      },
      include: {
        customer: { select: { id: true, name: true, email: true } },
        invoice: { select: { id: true, number: true } },
        items: { orderBy: { order: "asc" } },
      },
    });
  });

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