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

async function getOrgId(userId: string) {
}

export async function POST(
  _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 } });
  if (!note) return NextResponse.json({ success: false, error: "Introuvable" }, { status: 404 });
  if (note.status === "DELIVERED") {
    return NextResponse.json({ success: false, error: "Déjà livré" }, { status: 400 });
  }
  if (note.status === "CANCELLED") {
    return NextResponse.json({ success: false, error: "Ce bon est annulé" }, { status: 400 });
  }

  const updated = await prisma.deliveryNote.update({
    where: { id },
    data: { status: "DELIVERED", deliveredAt: new Date() },
  });

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