import { useState, useEffect } from "react";
import { useAuth } from "@/contexts/AuthContext";
import { supabase } from "@/integrations/supabase/client";

type AppRole = "admin" | "moderator" | "user";

interface AdminAuthState {
  isAdmin: boolean;
  isModerator: boolean;
  role: AppRole | null;
  loading: boolean;
}

export const useAdminAuth = () => {
  const { user } = useAuth();
  const [state, setState] = useState<AdminAuthState>({
    isAdmin: false,
    isModerator: false,
    role: null,
    loading: true,
  });

  useEffect(() => {
    const ensureProfileExists = async () => {
      if (!user) return;

      // The app relies on `public.profiles`, but a trigger may not exist in some setups.
      // This ensures the current user has a profile row (required for demo role bootstrap).
      const { data: existingProfile, error: selectError } = await supabase
        .from("profiles")
        .select("id")
        .eq("id", user.id)
        .maybeSingle();

      // If we can't read the profile (RLS/misconfig), don't block auth.
      if (selectError) return;

      if (existingProfile) return;

      const displayNameFromMeta = (user.user_metadata as any)?.display_name as string | undefined;
      const fallbackName = user.email ? user.email.split("@")[0] : null;

      // Insert is protected by RLS: auth.uid() must equal id
      await supabase.from("profiles").insert({
        id: user.id,
        email: user.email ?? null,
        display_name: displayNameFromMeta ?? fallbackName,
      });
    };

    const checkRole = async () => {
      if (!user) {
        setState({ isAdmin: false, isModerator: false, role: null, loading: false });
        return;
      }

      try {
        // Ensure the profile exists so the demo-role trigger (on profiles) can run.
        await ensureProfileExists();

        // Use the database function to check role - secure and cannot be bypassed client-side.
        const { data: userRole, error } = await supabase.rpc("get_user_role", {
          _user_id: user.id,
        });

        if (error) {
          console.error("Error fetching user role:", error);
          setState({ isAdmin: false, isModerator: false, role: null, loading: false });
          return;
        }

        const role = (userRole as AppRole | null) ?? "user";

        setState({
          isAdmin: role === "admin",
          isModerator: role === "admin" || role === "moderator",
          role,
          loading: false,
        });
      } catch (error) {
        console.error("Error in checkRole:", error);
        setState({ isAdmin: false, isModerator: false, role: null, loading: false });
      }
    };

    checkRole();
  }, [user]);

  return state;
};
