import { NextResponse } from "next/server";

import { auth } from "@/src/auth";
import { requirePermission } from "@/src/lib/auth/requireSession";
import { listMagazzini, createMagazzino } from "@/src/lib/stabilimenti";

export async function GET(request: Request) {
  const session = await auth();

  if (!session?.user) {
    return NextResponse.json({ error: "Non autorizzato" }, { status: 401 });
  }

  try {
    const { searchParams } = new URL(request.url);
    const stabilimentoId = searchParams.get("stabilimentoId");

    const magazzini = await listMagazzini(
      stabilimentoId ? parseInt(stabilimentoId, 10) : undefined
    );

    return NextResponse.json({ magazzini });
  } catch (error) {
    console.error("[API magazzini] Errore:", error);
    return NextResponse.json(
      { error: "Errore nel recupero dei magazzini" },
      { status: 500 }
    );
  }
}

export async function POST(request: Request) {
  const session = await requirePermission((p) => p.canManageStabilimenti);
  if (session instanceof NextResponse) return session;

  try {
    const magazzino = await createMagazzino(await request.json());
    return NextResponse.json({ magazzino }, { status: 201 });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore creazione magazzino" },
      { status: 400 }
    );
  }
}
