"use client";

import { useConvexAuth, useQuery } from "convex/react";
import { api } from "../../../../convex/_generated/api";

type AdminAuthState =
  | { status: "loading" }
  | { status: "authorized"; role: "admin" | "super_admin" }
  | { status: "denied"; reason: "not_authenticated" | "not_admin" | "no_user_record" };

export function useAdminAuth(): AdminAuthState {
  const { isLoading, isAuthenticated } = useConvexAuth();
  const user = useQuery(
    api.users.current,
    isAuthenticated ? {} : "skip",
  );

  if (isLoading) return { status: "loading" };
  if (!isAuthenticated) return { status: "denied", reason: "not_authenticated" };
  if (user === undefined) return { status: "loading" };
  if (user === null) return { status: "denied", reason: "no_user_record" };
  if (user.role !== "admin" && user.role !== "super_admin") {
    return { status: "denied", reason: "not_admin" };
  }
  return { status: "authorized", role: user.role };
}
