import { NextResponse } from "next/server";

import { auth } from "@/src/auth";
import { listStabilimenti, getStabilimentiWithMagazzini } 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 includeMagazzini = searchParams.get("includeMagazzini") === "true";

    if (includeMagazzini) {
      const stabilimenti = await getStabilimentiWithMagazzini();
      return NextResponse.json({ stabilimenti });
    }

    const stabilimenti = await listStabilimenti();
    return NextResponse.json({ stabilimenti });
  } catch (error) {
    console.error("[API stabilimenti] Errore:", error);
    return NextResponse.json(
      { error: "Errore nel recupero degli stabilimenti" },
      { status: 500 }
    );
  }
}
