"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { getMe } from "@/lib/api";
import { getCachedUser, setCachedUser } from "@/lib/auth-cache";

export { clearAuthCache } from "@/lib/auth-cache";

// Role hierarchy: superadmin(5) > domain_admin(4) > domain_auditor(3) > auditor(2) > user(1)
const roleLevels: Record<string, number> = {
  user: 1,
  auditor: 2,
  domain_auditor: 3,
  admin: 3,        // legacy alias
  domain_admin: 4,
  superadmin: 5,
};

export function hasRole(userRole: string, required: string): boolean {
  return (roleLevels[userRole] ?? 0) >= (roleLevels[required] ?? 0);
}

export function useAuth(requireRole?: "admin" | "domain_admin" | "superadmin" | "auditor", loginPage = "/") {
  const router = useRouter();
  const cached = getCachedUser();
  const [user, setUser] = useState(cached);
  const [loading, setLoading] = useState(cached === null);

  const checkAuth = useCallback(async () => {
    const cached = getCachedUser();
    if (cached !== null) {
      if (requireRole && !hasRole(cached.role, requireRole)) {
        router.replace("/search");
        return;
      }
      setUser(cached);
      setLoading(false);
      return;
    }

    try {
      const me = await getMe();
      setCachedUser(me);
      if (requireRole && !hasRole(me.role, requireRole)) {
        router.replace("/search");
        return;
      }
      setUser(me);
      setLoading(false);
    } catch {
      setCachedUser(null);
      router.replace(loginPage);
    }
  }, [router, requireRole, loginPage]);

  useEffect(() => {
    checkAuth();
  }, [checkAuth]);

  const refresh = useCallback(async () => {
    try {
      const me = await getMe();
      setCachedUser(me);
      setUser(me);
    } catch {
      // ignore refresh errors, keep existing cached user
    }
  }, []);

  return { user, loading, refresh };
}
