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

interface RecentChange {
  id: string;
  name: string;
  type: 'park' | 'ride' | 'company';
  slug: string;
  parkSlug?: string;
  imageUrl?: string;
  changeType: string;
  changedAt: string;
  changedBy?: {
    username: string;
    avatarUrl?: string;
  };
  changeReason?: string;
}

export function useHomepageRecentChanges(enabled = true) {
  return useQuery({
    queryKey: queryKeys.homepage.recentChanges(),
    queryFn: async () => {
      // Use the new database function to get all changes in a single query
      const { data, error } = await supabase.rpc('get_recent_changes', { limit_count: 24 });
      
      if (error) throw error;
      
      // Transform the database response to match our interface
      return (data || []).map((item: any) => ({
        id: item.entity_id,
        name: item.entity_name,
        type: item.entity_type as 'park' | 'ride' | 'company',
        slug: item.entity_slug,
        parkSlug: item.park_slug || undefined,
        imageUrl: item.image_url || undefined,
        changeType: item.change_type,
        changedAt: item.changed_at,
        changedBy: item.changed_by_username ? {
          username: item.changed_by_username,
          avatarUrl: item.changed_by_avatar || undefined
        } : undefined,
        changeReason: item.change_reason || undefined
      })) as RecentChange[];
    },
    enabled,
    staleTime: 5 * 60 * 1000,
    gcTime: 15 * 60 * 1000,
    refetchOnWindowFocus: false,
  });
}
