import { useQuery, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { Profile } from '@/types/database';
import { getErrorMessage } from '@/lib/errorHandler';

export function useProfile(userId: string | undefined) {
  const queryClient = useQueryClient();

  const query = useQuery({
    queryKey: ['profile', userId],
    queryFn: async () => {
      if (!userId) return null;
      
      // Get current viewer ID
      const { data: { user } } = await supabase.auth.getUser();
      const viewerId = user?.id || null;
      
      // Use get_filtered_profile RPC for privacy-aware field filtering
      const { data, error } = await supabase.rpc('get_filtered_profile', {
        _profile_user_id: userId,
        _viewer_id: viewerId || ''
      });
      
      if (error) {
        throw error;
      }
      
      if (!data) return null;
      
      // Type the JSONB response properly
      const profileData = data as unknown as Profile;
      
      // Fetch location separately if location_id is present and visible
      if (profileData.location_id) {
        const { data: location } = await supabase
          .from('locations')
          .select('id, name, city, state_province, country, timezone')
          .eq('id', profileData.location_id)
          .single();
        
        if (location) {
          profileData.location = location;
        }
      }
      
      return profileData;
    },
    enabled: !!userId,
    staleTime: 5 * 60 * 1000, // 5 minutes
    refetchOnWindowFocus: false,
    retry: 2,
  });

  const refreshProfile = () => {
    if (userId) {
      queryClient.invalidateQueries({ queryKey: ['profile', userId] });
    }
  };

  return {
    ...query,
    refreshProfile,
  };
}
