import { NextResponse } from "next/server";

import { auth } from "@/src/auth";
import { requirePermission } from "@/src/lib/auth/requireSession";
import {
  getStabilimentoById,
  updateStabilimento,
  deleteStabilimento,
} from "@/src/lib/stabilimenti";

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

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

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

  return stabilimentoId;
}

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 stabilimento = await getStabilimentoById(await readId(context.params));
    if (!stabilimento) {
      return NextResponse.json({ error: "Stabilimento non trovato" }, { status: 404 });
    }
    return NextResponse.json({ stabilimento });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore recupero stabilimento" },
      { 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 stabilimento = await updateStabilimento(
      await readId(context.params),
      await request.json()
    );
    return NextResponse.json({ stabilimento });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore modifica stabilimento" },
      { 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 deleteStabilimento(await readId(context.params));
    return NextResponse.json({ ok: true });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore eliminazione stabilimento" },
      { status: 400 }
    );
  }
}
