import { useEffect } from 'react';
import { createClient } from '@/lib/supabase/client';
import { db } from '@/lib/db';
import { getAllSystemTags } from '@/services/tags';

export function useCacheSync() {
    const supabase = createClient();

    useEffect(() => {
        const syncCache = async () => {
            if (!navigator.onLine) return;

            try {
                // 1. Sync Tags
                const tags = await getAllSystemTags();
                if (tags.length > 0) {
                    await db.cache_tags.bulkPut(tags.map(t => ({
                        id: t.id,
                        name: t.name,
                        category: t.category,
                        is_system_default: t.is_system_default,
                        popularity_score: t.popularity_score || 0
                    })));
                }

                // 2. Sync Buddies
                const { data: buddies } = await supabase
                    .from('buddies')
                    .select('id, name')
                    .order('name');

                if (buddies && buddies.length > 0) {
                    await db.cache_buddies.bulkPut(buddies);
                }
            } catch (err) {
                console.error('Failed to sync offline cache:', err);
            }
        };

        syncCache();
        window.addEventListener('online', syncCache);
        return () => window.removeEventListener('online', syncCache);
    }, [supabase]);
}
