/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/financeiro/composables/useBillingContracts.js
|
| Thin wrapper sobre billingContractsRepository. Operações de pacote/contrato:
| listForPatient, fetchById, create, update, increment/decrement sessions_used.
|
| Gotcha: billing_contracts não tem updated_at — repository já strips.
|--------------------------------------------------------------------------
*/
import { ref } from 'vue';
import {
    listForPatient,
    getById,
    create as repoCreate,
    update as repoUpdate,
    incrementSessionsUsed,
    decrementSessionsUsed
} from '@/features/financeiro/services/billingContractsRepository';

export function useBillingContracts() {
    const rows = ref([]);
    const loading = ref(false);
    const error = ref('');

    async function loadForPatient(patientId, opts = {}) {
        if (!patientId) {
            rows.value = [];
            return;
        }
        loading.value = true;
        error.value = '';
        try {
            rows.value = await listForPatient(patientId, opts);
        } catch (e) {
            error.value = e?.message || 'Falha ao carregar contratos.';
            rows.value = [];
        } finally {
            loading.value = false;
        }
    }

    async function fetchById(contractId, opts = {}) {
        try {
            return await getById(contractId, opts);
        } catch (e) {
            error.value = e?.message || 'Falha ao carregar contrato.';
            return null;
        }
    }

    async function create(payload) {
        loading.value = true;
        error.value = '';
        try {
            const created = await repoCreate(payload);
            rows.value = [created, ...rows.value];
            return created;
        } catch (e) {
            error.value = e?.message || 'Falha ao criar contrato.';
            throw e;
        } finally {
            loading.value = false;
        }
    }

    async function update(contractId, patch, opts = {}) {
        loading.value = true;
        error.value = '';
        try {
            const updated = await repoUpdate(contractId, patch, opts);
            const idx = rows.value.findIndex((r) => r.id === contractId);
            if (idx >= 0) rows.value[idx] = updated;
            return updated;
        } catch (e) {
            error.value = e?.message || 'Falha ao atualizar contrato.';
            throw e;
        } finally {
            loading.value = false;
        }
    }

    async function consume(contractId, opts = {}) {
        error.value = '';
        try {
            const updated = await incrementSessionsUsed(contractId, opts);
            const idx = rows.value.findIndex((r) => r.id === contractId);
            if (idx >= 0) rows.value[idx] = updated;
            return updated;
        } catch (e) {
            error.value = e?.message || 'Falha ao incrementar saldo.';
            throw e;
        }
    }

    async function returnSession(contractId, opts = {}) {
        error.value = '';
        try {
            const updated = await decrementSessionsUsed(contractId, opts);
            const idx = rows.value.findIndex((r) => r.id === contractId);
            if (idx >= 0) rows.value[idx] = updated;
            return updated;
        } catch (e) {
            error.value = e?.message || 'Falha ao devolver saldo.';
            throw e;
        }
    }

    return {
        rows,
        loading,
        error,
        loadForPatient,
        fetchById,
        create,
        update,
        consume,
        returnSession
    };
}
