import { NextResponse } from "next/server";

import { forbid, requirePermission } from "@/src/lib/auth/requireSession";
import { deleteUser, getUserById, updateUser } from "@/src/lib/users";

type RouteContext = { params: Promise<{ id: string }> };

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

  const { id } = await context.params;
  const userId = parseInt(id, 10);

  if (!Number.isInteger(userId) || userId <= 0) {
    return NextResponse.json({ error: "ID non valido" }, { status: 400 });
  }

  try {
    const utente = await getUserById(userId);
    if (!utente) {
      return NextResponse.json({ error: "Utente non trovato" }, { status: 404 });
    }
    return NextResponse.json({ utente });
  } catch (error) {
    console.error("[API utenti/id] Errore GET:", error);
    return NextResponse.json({ error: "Errore nel recupero" }, { status: 500 });
  }
}

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

  const { id } = await context.params;
  const userId = parseInt(id, 10);
  const currentId = parseInt(session.user.id, 10);

  if (!Number.isInteger(userId) || userId <= 0) {
    return NextResponse.json({ error: "ID non valido" }, { status: 400 });
  }

  try {
    const body = await request.json();

    if (userId === currentId && body.ruolo && body.ruolo !== session.user.ruolo) {
      return forbid("Non puoi modificare il tuo ruolo.");
    }
    if (userId === currentId && body.attivo === 0) {
      return forbid("Non puoi disattivare il tuo account.");
    }

    const utente = await updateUser(userId, body);
    return NextResponse.json({ utente });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore aggiornamento" },
      { status: 400 },
    );
  }
}

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

  const { id } = await context.params;
  const userId = parseInt(id, 10);
  const currentId = parseInt(session.user.id, 10);

  if (!Number.isInteger(userId) || userId <= 0) {
    return NextResponse.json({ error: "ID non valido" }, { status: 400 });
  }

  if (userId === currentId) {
    return forbid("Non puoi eliminare il tuo account.");
  }

  try {
    await deleteUser(userId);
    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Errore eliminazione" },
      { status: 400 },
    );
  }
}
