/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/documents/composables/useDocumentSignatures.js
| Composable Tipo A (thin wrapper) sobre DocumentSignatures.service.
|--------------------------------------------------------------------------
*/
import { ref } from 'vue';
import {
    createSignatureRequests,
    listSignatures,
    getSignatureStatus,
    refuseSignature,
    signByPortal,
    signByToken,
    getSignableDocumentByToken,
    listMySignatures,
    hashDocument
} from '@/services/DocumentSignatures.service';

export function useDocumentSignatures() {
    const signatures = ref([]);
    const loading = ref(false);
    const error = ref('');
    const status = ref(null); // { total, assinados, pendentes, status }

    async function fetchForDocument(documentoId) {
        if (!documentoId) {
            signatures.value = [];
            status.value = null;
            return [];
        }
        loading.value = true;
        error.value = '';
        try {
            const [list, st] = await Promise.all([
                listSignatures(documentoId),
                getSignatureStatus(documentoId)
            ]);
            signatures.value = Array.isArray(list) ? list : [];
            status.value = st || null;
            return signatures.value;
        } catch (e) {
            error.value = e?.message || 'Falha ao carregar assinaturas.';
            signatures.value = [];
            status.value = null;
            throw e;
        } finally {
            loading.value = false;
        }
    }

    async function requestSignatures(documentoId, signatarios = []) {
        loading.value = true;
        error.value = '';
        try {
            const rows = await createSignatureRequests(documentoId, signatarios);
            signatures.value = [...signatures.value, ...rows];
            return rows;
        } catch (e) {
            error.value = e?.message || 'Falha ao solicitar assinaturas.';
            throw e;
        } finally {
            loading.value = false;
        }
    }

    async function sign(signatureId, { hashDocumento = null, tenantId = null } = {}) {
        loading.value = true;
        error.value = '';
        try {
            // schema-per-tenant: a assinatura vive no schema do tenant. Resolve o
            // tenant_id da própria linha (list_my_signatures retorna tenant_id) ou
            // do parâmetro explícito.
            const row = signatures.value.find(s => (s.signature_id ?? s.id) === signatureId);
            const tid = tenantId || row?.tenant_id;
            const updated = await signByPortal(tid, signatureId, hashDocumento);
            const idx = signatures.value.findIndex(s => (s.signature_id ?? s.id) === signatureId);
            if (idx >= 0) signatures.value.splice(idx, 1, updated);
            return updated;
        } catch (e) {
            error.value = e?.message || 'Falha ao assinar documento.';
            throw e;
        } finally {
            loading.value = false;
        }
    }

    async function refuse(signatureId) {
        loading.value = true;
        error.value = '';
        try {
            const updated = await refuseSignature(signatureId);
            const idx = signatures.value.findIndex(s => s.id === signatureId);
            if (idx >= 0) signatures.value.splice(idx, 1, updated);
            return updated;
        } catch (e) {
            error.value = e?.message || 'Falha ao recusar assinatura.';
            throw e;
        } finally {
            loading.value = false;
        }
    }

    async function signWithToken(token, signatureId = null, { hashDocumento = null } = {}) {
        loading.value = true;
        error.value = '';
        try {
            return await signByToken(token, signatureId, hashDocumento);
        } catch (e) {
            error.value = e?.message || 'Falha ao assinar via link.';
            throw e;
        } finally {
            loading.value = false;
        }
    }

    async function loadMine(statusFilter = null) {
        loading.value = true;
        error.value = '';
        try {
            const rows = await listMySignatures(statusFilter);
            signatures.value = Array.isArray(rows) ? rows : [];
            return signatures.value;
        } catch (e) {
            error.value = e?.message || 'Falha ao carregar minhas assinaturas.';
            signatures.value = [];
            throw e;
        } finally {
            loading.value = false;
        }
    }

    async function loadByToken(token) {
        loading.value = true;
        error.value = '';
        try {
            const payload = await getSignableDocumentByToken(token);
            if (!payload?.valid) {
                error.value = payload?.error === 'expired_or_invalid'
                    ? 'Link expirado ou inválido.'
                    : payload?.error === 'document_not_found'
                        ? 'Documento não encontrado.'
                        : 'Token inválido.';
                return null;
            }
            signatures.value = Array.isArray(payload.signatures) ? payload.signatures : [];
            return payload;
        } catch (e) {
            error.value = e?.message || 'Falha ao validar token.';
            throw e;
        } finally {
            loading.value = false;
        }
    }

    return {
        signatures,
        status,
        loading,
        error,
        fetchForDocument,
        requestSignatures,
        sign,
        refuse,
        signWithToken,
        loadByToken,
        loadMine,
        hashDocument
    };
}
