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

async function getOrgId(userId: string) {
}

const updateSchema = z.object({
  customerId: z.string().nullable().optional(),
  invoiceId: z.string().nullable().optional(),
  deliveryDate: z.string().nullable().optional(),
  shippingAddress: z.string().nullable().optional(),
  notes: z.string().nullable().optional(),
  reference: z.string().nullable().optional(),
}).strict();

// ─── GET /api/delivery-notes/[id] ─────────────────────────────

export async function GET(
  _req: 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;
  if (!orgId) return NextResponse.json({ success: false, error: "Organisation introuvable" }, { status: 404 });

  const { id } = await params;
  const note = await prisma.deliveryNote.findFirst({
    where: { id, organizationId: orgId },
    include: {
      customer: { select: { id: true, name: true, email: true, phone: true, address: true, city: true } },
      invoice: { select: { id: true, number: true } },
      items: { orderBy: { order: "asc" } },
    },
  });

  if (!note) return NextResponse.json({ success: false, error: "Bon de livraison introuvable" }, { status: 404 });

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

// ─── PATCH /api/delivery-notes/[id] ───────────────────────────

export async function PATCH(
  req: 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;
  if (!orgId) return NextResponse.json({ success: false, error: "Organisation introuvable" }, { status: 404 });

  const { id } = await params;
  const existing = await prisma.deliveryNote.findFirst({ where: { id, organizationId: orgId } });
  if (!existing) return NextResponse.json({ success: false, error: "Introuvable" }, { status: 404 });
  if (existing.status === "DELIVERED" || existing.status === "CANCELLED") {
    return NextResponse.json({ success: false, error: "Ce bon de livraison ne peut plus être modifié" }, { status: 400 });
  }

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

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

  const { deliveryDate, ...rest } = parsed.data;
  const updated = await prisma.deliveryNote.update({
    where: { id },
    data: {
      ...rest,
      ...(deliveryDate !== undefined && { deliveryDate: deliveryDate ? new Date(deliveryDate) : null }),
    },
    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: updated });
}

// ─── DELETE /api/delivery-notes/[id] ──────────────────────────

export async function DELETE(
  _req: 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;
  if (!orgId) return NextResponse.json({ success: false, error: "Organisation introuvable" }, { status: 404 });

  const { id } = await params;
  const existing = await prisma.deliveryNote.findFirst({ where: { id, organizationId: orgId } });
  if (!existing) return NextResponse.json({ success: false, error: "Introuvable" }, { status: 404 });
  if (existing.status === "DELIVERED") {
    return NextResponse.json({ success: false, error: "Un bon livré ne peut pas être supprimé" }, { status: 400 });
  }

  await prisma.deliveryNote.delete({ where: { id } });
  return NextResponse.json({ success: true });
}
