/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/composables/useWhatsappCredits.js
| Data: 2026-04-21
|
| Sistema de créditos WhatsApp (Marco B).
|--------------------------------------------------------------------------
*/

import { ref, computed } from 'vue';
import { supabase } from '@/lib/supabase/client';
import { useTenantStore } from '@/stores/tenantStore';

export function useWhatsappCredits() {
    const tenantStore = useTenantStore();

    const balance = ref(null);           // { balance, lifetime_purchased, lifetime_used, low_balance_threshold }
    const transactions = ref([]);        // últimos extratos
    const packages = ref([]);            // pacotes ativos (loja)
    const purchases = ref([]);           // minhas ordens de compra
    const tenantCpfCnpj = ref('');       // CPF/CNPJ armazenado no tenant (pra prefill)
    const loading = ref(false);
    const creating = ref(false);

    const currentBalance = computed(() => balance.value?.balance ?? 0);
    const isLow = computed(() => {
        if (!balance.value) return false;
        return balance.value.balance <= balance.value.low_balance_threshold;
    });

    async function loadAll() {
        const tenantId = tenantStore.activeTenantId;
        if (!tenantId) return;
        loading.value = true;
        try {
            const [balRes, txRes, pkgRes, purRes, tenRes] = await Promise.all([
                supabase
                    .from('whatsapp_credits_balance')
                    .select('*')
                    .eq('tenant_id', tenantId)
                    .maybeSingle(),
                supabase
                    .from('whatsapp_credits_transactions')
                    .select('id, kind, amount, balance_after, note, created_at, purchase_id, admin_id')
                    .eq('tenant_id', tenantId)
                    .order('created_at', { ascending: false })
                    .limit(50),
                supabase
                    .from('whatsapp_credit_packages')
                    .select('*')
                    .eq('is_active', true)
                    .order('position', { ascending: true })
                    .order('price_brl', { ascending: true }),
                supabase
                    .from('whatsapp_credit_purchases')
                    .select('id, package_name, credits, amount_brl, status, paid_at, expires_at, created_at, asaas_pix_qrcode, asaas_pix_copy_paste, asaas_payment_link')
                    .eq('tenant_id', tenantId)
                    .order('created_at', { ascending: false })
                    .limit(20),
                supabase
                    .from('tenants')
                    .select('cpf_cnpj')
                    .eq('id', tenantId)
                    .maybeSingle()
            ]);

            balance.value = balRes.data || { balance: 0, lifetime_purchased: 0, lifetime_used: 0, low_balance_threshold: 20 };
            transactions.value = txRes.data || [];
            packages.value = pkgRes.data || [];
            purchases.value = purRes.data || [];
            tenantCpfCnpj.value = tenRes.data?.cpf_cnpj || '';
        } catch (e) {
            console.error('[useWhatsappCredits] loadAll:', e?.message);
        } finally {
            loading.value = false;
        }
    }

    async function createPurchase(packageId, cpfCnpj = null) {
        if (!packageId) return { ok: false, error: 'package_missing' };
        creating.value = true;
        try {
            const cleanDoc = (cpfCnpj || '').replace(/\D/g, '') || null;
            const body = cleanDoc ? { package_id: packageId, cpf_cnpj: cleanDoc } : { package_id: packageId };
            const { data, error } = await supabase.functions.invoke('create-whatsapp-credit-charge', { body });
            if (error) {
                // Edge function errors (non-2xx) vêm em error.context.json() no SDK novo
                let parsed = null;
                try {
                    parsed = typeof error.context?.json === 'function'
                        ? await error.context.json()
                        : null;
                } catch (_) { /* swallow */ }
                return {
                    ok: false,
                    error: parsed?.error || error.message || 'invoke_failed',
                    message: parsed?.message || null
                };
            }
            if (!data?.ok) return { ok: false, error: data?.error || 'unknown', message: data?.message || null };
            // Atualiza CPF armazenado se a compra foi com um novo
            if (cleanDoc) tenantCpfCnpj.value = cleanDoc;
            await loadAll();
            return { ok: true, purchase: data.purchase };
        } catch (e) {
            return { ok: false, error: e?.message || 'create_failed' };
        } finally {
            creating.value = false;
        }
    }

    async function updateLowBalanceThreshold(newThreshold) {
        const tenantId = tenantStore.activeTenantId;
        if (!tenantId) return { ok: false, error: 'no_tenant' };
        const v = Math.max(0, Math.min(10000, Number(newThreshold) || 0));
        try {
            const { error } = await supabase
                .from('whatsapp_credits_balance')
                .upsert({ tenant_id: tenantId, low_balance_threshold: v }, { onConflict: 'tenant_id' });
            if (error) throw error;
            if (balance.value) balance.value.low_balance_threshold = v;
            return { ok: true };
        } catch (e) {
            return { ok: false, error: e?.message || 'update_failed' };
        }
    }

    return {
        balance,
        transactions,
        packages,
        purchases,
        tenantCpfCnpj,
        currentBalance,
        isLow,
        loading,
        creating,
        loadAll,
        createPurchase,
        updateLowBalanceThreshold
    };
}
