import { NextResponse } from "next/server";

import { auth } from "@/src/auth";
import { requirePermission } from "@/src/lib/auth/requireSession";
import {
  listStabilimenti,
  getStabilimentiWithMagazzini,
  createStabilimento,
} 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 }
    );
  }
}

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

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