/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/composables/useLgpdExport.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 { useTenantStore } from '@/stores/tenantStore';
import { downloadLgpdPDF } from '@/utils/lgpdExportFormats';

function slugify(s) {
    if (!s) return 'paciente';
    return (
        String(s)
            .toLowerCase()
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/(^-|-$)/g, '')
            .slice(0, 40) || 'paciente'
    );
}

function downloadBlob(blob, filename) {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

export function useLgpdExport() {
    const loading = ref(false);
    const error = ref(null);
    const lastPayload = ref(null);

    async function fetchExport(patientId) {
        if (!patientId) {
            throw new Error('patientId obrigatório');
        }

        const tenantId = useTenantStore().activeTenantId;
        const { data, error: rpcErr } = await supabase.rpc('export_patient_data', { p_tenant_id: tenantId, p_patient_id: patientId });
        if (rpcErr) throw rpcErr;
        return data;
    }

    async function exportJSON(patientId, patientName) {
        loading.value = true;
        error.value = null;
        try {
            const payload = await fetchExport(patientId);
            lastPayload.value = payload;

            const ts = new Date().toISOString().slice(0, 10);
            const filename = `lgpd-export-${slugify(patientName)}-${ts}.json`;
            const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json;charset=utf-8' });
            downloadBlob(blob, filename);
            return payload;
        } catch (err) {
            error.value = err;
            throw err;
        } finally {
            loading.value = false;
        }
    }

    async function exportPDF(patientId, patientName, tenantName) {
        loading.value = true;
        error.value = null;
        try {
            const payload = await fetchExport(patientId);
            lastPayload.value = payload;

            const ts = new Date().toISOString().slice(0, 10);
            const filename = `lgpd-export-${slugify(patientName)}-${ts}.pdf`;
            await downloadLgpdPDF(payload, tenantName, filename);
            return payload;
        } catch (err) {
            error.value = err;
            throw err;
        } finally {
            loading.value = false;
        }
    }

    return {
        loading,
        error,
        lastPayload,
        fetchExport,
        exportJSON,
        exportPDF
    };
}
