import { useQuery } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/hooks/useAuth';
import { queryKeys } from '@/lib/queryKeys';

export type UserRole = 'admin' | 'moderator' | 'user' | 'superuser';

export interface UserPermissions {
  can_ban_any_user: boolean;
  can_manage_admin_roles: boolean;
  can_manage_moderator_roles: boolean;
  can_view_all_profiles: boolean;
  can_assign_superuser: boolean;
  role_level: string;
}

export function useUserRole() {
  const { user } = useAuth();

  // Fetch user roles with TanStack Query for automatic caching
  const rolesQuery = useQuery({
    queryKey: queryKeys.userRoles(user?.id),
    queryFn: async () => {
      if (!user) return [];
      
      const { data, error } = await supabase
        .from('user_roles')
        .select('role')
        .eq('user_id', user.id);
      
      if (error) {
        console.error('Error fetching user roles:', error);
        return [];
      }
      
      return data?.map(r => r.role as UserRole) || [];
    },
    enabled: !!user,
    staleTime: 5 * 60 * 1000, // 5 minutes - roles don't change often
    gcTime: 10 * 60 * 1000,    // 10 minutes garbage collection
  });

  // Fetch user permissions with TanStack Query for automatic caching
  const permissionsQuery = useQuery({
    queryKey: queryKeys.userPermissions(user?.id),
    queryFn: async () => {
      if (!user) return null;
      
      const { data, error } = await supabase
        .rpc('get_user_management_permissions', { _user_id: user.id });
      
      if (error) {
        console.error('Error fetching user permissions:', error);
        return null;
      }
      
      return data as unknown as UserPermissions;
    },
    enabled: !!user,
    staleTime: 5 * 60 * 1000, // 5 minutes - permissions don't change often
    gcTime: 10 * 60 * 1000,    // 10 minutes garbage collection
  });

  const roles = rolesQuery.data || [];
  const permissions = permissionsQuery.data || null;
  const loading = rolesQuery.isLoading || permissionsQuery.isLoading;

  const hasRole = (role: UserRole) => roles.includes(role);
  const isModerator = () => hasRole('admin') || hasRole('moderator') || hasRole('superuser');
  const isAdmin = () => hasRole('admin') || hasRole('superuser');
  const isSuperuser = () => hasRole('superuser');

  return {
    roles,
    permissions,
    loading,
    hasRole,
    isModerator,
    isAdmin,
    isSuperuser
  };
}