import { NextResponse } from "next/server";

import { auth } from "@/src/auth";
import {
  getPermissions,
  normalizeRole,
  type AppPermissions,
} from "@/src/lib/permissions";
import type { UserRole } from "@/src/types/user";

export type AuthSession = {
  user: {
    id: string;
    ruolo: UserRole;
    utente: string;
    name?: string | null;
    email?: string | null;
  };
  permissions: AppPermissions;
};

export async function requireSession(): Promise<AuthSession | NextResponse> {
  const session = await auth();

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

  const ruolo = normalizeRole(session.user.ruolo);
  if (!ruolo) {
    return NextResponse.json({ error: "Ruolo utente non valido" }, { status: 403 });
  }

  return {
    user: {
      id: session.user.id,
      ruolo,
      utente: session.user.utente,
      name: session.user.name,
      email: session.user.email,
    },
    permissions: getPermissions(ruolo),
  };
}

export function forbid(message = "Accesso negato"): NextResponse {
  return NextResponse.json({ error: message }, { status: 403 });
}

export async function requirePermission(
  check: (permissions: AppPermissions) => boolean,
  message = "Accesso negato",
): Promise<AuthSession | NextResponse> {
  const result = await requireSession();
  if (result instanceof NextResponse) return result;

  if (!check(result.permissions)) {
    return forbid(message);
  }

  return result;
}
