import { NextResponse } from "next/server";

import { auth } from "@/src/auth";
import { requirePermission } from "@/src/lib/auth/requireSession";
import { getMagazzinoById, updateMagazzino, deleteMagazzino } from "@/src/lib/stabilimenti";

interface RouteContext {
  params: Promise<{ id: string }>;
}

async function readId(params: Promise<{ id: string }>): Promise<number> {
  const { id } = await params;
  const magazzinoId = Number(id);

  if (!Number.isInteger(magazzinoId) || magazzinoId <= 0) {
    throw new Error("ID magazzino non valido.");
  }

  return magazzinoId;
}

export async function GET(_request: Request, context: RouteContext) {
  const session = await auth();

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

  try {
    const magazzino = await getMagazzinoById(await readId(context.params));
    if (!magazzino) {
      return NextResponse.json({ error: "Magazzino non trovato" }, { status: 404 });
    }
    return NextResponse.json({ magazzino });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore recupero magazzino" },
      { status: 400 }
    );
  }
}

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

  try {
    const magazzino = await updateMagazzino(
      await readId(context.params),
      await request.json()
    );
    return NextResponse.json({ magazzino });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore modifica magazzino" },
      { status: 400 }
    );
  }
}

export async function DELETE(_request: Request, context: RouteContext) {
  const session = await requirePermission((p) => p.canManageStabilimenti);
  if (session instanceof NextResponse) return session;

  try {
    await deleteMagazzino(await readId(context.params));
    return NextResponse.json({ ok: true });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore eliminazione magazzino" },
      { status: 400 }
    );
  }
}
