/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/composables/useUserSettingsPersistence.js
| Data: 2026
| Local: São Carlos/SP — Brasil
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
*/
import { ref } from 'vue';
import { supabase } from '@/lib/supabase/client';
import { useLayout } from '@/layout/composables/layout';

export function useUserSettingsPersistence() {
    const { layoutConfig } = useLayout();

    const userId = ref('');
    const saveTimer = ref(null);
    const pendingPatch = ref({});
    const initializing = ref(false);

    function isDarkNow() {
        return document.documentElement.classList.contains('app-dark');
    }

    async function init() {
        if (initializing.value) return;
        initializing.value = true;
        try {
            const { data, error } = await supabase.auth.getUser();
            if (error) throw error;
            userId.value = data?.user?.id || '';
            console.log('[user_settings] init userId =', userId.value);
        } finally {
            initializing.value = false;
        }
    }

    async function flush() {
        if (!userId.value) {
            console.warn('[user_settings] flush cancelado: sem userId');
            return;
        }

        const patch = { ...pendingPatch.value };
        pendingPatch.value = {};

        const payload = {
            user_id: userId.value,
            theme_mode: patch.theme_mode ?? (isDarkNow() ? 'dark' : 'light'),
            preset: patch.preset ?? layoutConfig.preset ?? 'Aura',
            primary_color: patch.primary_color ?? layoutConfig.primary ?? 'noir',
            surface_color: patch.surface_color ?? layoutConfig.surface ?? 'slate',
            menu_mode: patch.menu_mode ?? layoutConfig.menuMode ?? 'static',
            layout_variant: patch.layout_variant ?? layoutConfig.variant ?? 'classic',
            updated_at: new Date().toISOString()
        };

        console.log('[user_settings] flush payload =', payload);

        const { error } = await supabase.from('user_settings').upsert(payload, { onConflict: 'user_id' });

        if (error) {
            console.error('[user_settings] flush falhou:', error.message || error);
            throw error;
        }
    }

    /**
     * @param {object} patch
     * @param {object} opts
     * @param {number} opts.debounceMs
     * @param {boolean} opts.flushNow
     */
    function queuePatch(patch, opts = {}) {
        const debounceMs = typeof opts.debounceMs === 'number' ? opts.debounceMs : 500;
        const flushNow = !!opts.flushNow;

        pendingPatch.value = { ...pendingPatch.value, ...patch };

        if (saveTimer.value) clearTimeout(saveTimer.value);

        const run = async () => {
            if (!userId.value) return;

            const payload = {
                user_id: userId.value,
                theme_mode: pendingPatch.value.theme_mode ?? (isDarkNow() ? 'dark' : 'light'),
                preset: pendingPatch.value.preset ?? layoutConfig.preset,
                primary_color: pendingPatch.value.primary_color ?? layoutConfig.primary,
                surface_color: pendingPatch.value.surface_color ?? layoutConfig.surface,
                menu_mode: pendingPatch.value.menu_mode ?? layoutConfig.menuMode,
                layout_variant: pendingPatch.value.layout_variant ?? layoutConfig.variant ?? 'classic',
                updated_at: new Date().toISOString()
            };

            pendingPatch.value = {};

            const { error } = await supabase.from('user_settings').upsert(payload, { onConflict: 'user_id' });

            if (error) {
                console.error('[user_settings] save falhou:', error?.message || error, payload);
                throw error;
            }

            console.log('[user_settings] saved:', payload);
        };

        if (flushNow) return run();

        saveTimer.value = setTimeout(run, debounceMs);
    }

    return {
        init,
        queuePatch,
        flush
    };
}
