import { NextResponse } from "next/server";

import { requirePermission } from "@/src/lib/auth/requireSession";
import { createUser, listUsers } from "@/src/lib/users";

export async function GET() {
  const session = await requirePermission((p) => p.canManageUtenti);
  if (session instanceof NextResponse) return session;

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

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

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