import { useState, useCallback, useRef } from 'react';
import { supabase } from '@/integrations/supabase/client';

const rulesCache = new Map();

export function useFinancialRulesCache(associationId) {
  const [rules, setRules] = useState(rulesCache.get(associationId) || []);
  const [loading, setLoading] = useState(false);
  const fetchPromise = useRef(null);

  const fetchRules = useCallback(async (forceRefresh = false) => {
    if (!associationId) return [];
    if (!forceRefresh && rulesCache.has(associationId)) {
      const cached = rulesCache.get(associationId);
      setRules(cached);
      return cached;
    }

    if (fetchPromise.current) return fetchPromise.current;

    setLoading(true);
    fetchPromise.current = (async () => {
      try {
        const { data, error } = await supabase
          .from('journal_entries')
          .select('*')
          .eq('association_id', associationId);
        
        if (error) throw error;
        const fetchedRules = data || [];
        rulesCache.set(associationId, fetchedRules);
        setRules(fetchedRules);
        return fetchedRules;
      } catch (err) {
        console.error('Error fetching rules:', err);
        return [];
      } finally {
        setLoading(false);
        fetchPromise.current = null;
      }
    })();

    return fetchPromise.current;
  }, [associationId]);

  return { rules, loading, fetchRules };
}
