/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/insurance/composables/useInsurancePlans.js
|
| Thin wrapper sobre insurancePlansRepository.
| Pattern: composable-blueprint Tipo A (default).
|--------------------------------------------------------------------------
*/
import { ref } from 'vue';
import { listForOwner, getById, findByName, create as repoCreate, update as repoUpdate, softDelete as repoSoftDelete } from '@/features/insurance/services/insurancePlansRepository';

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

    async function loadForOwner(opts = {}) {
        loading.value = true;
        error.value = '';
        try {
            rows.value = await listForOwner(opts);
        } catch (e) {
            error.value = e?.message || 'Falha ao carregar convênios.';
            rows.value = [];
        } finally {
            loading.value = false;
        }
    }

    async function fetchById(id, opts = {}) {
        loading.value = true;
        error.value = '';
        try {
            return await getById(id, opts);
        } catch (e) {
            error.value = e?.message || 'Falha ao carregar convênio.';
            return null;
        } finally {
            loading.value = false;
        }
    }

    async function create(payload) {
        loading.value = true;
        error.value = '';
        try {
            const created = await repoCreate(payload);
            if (created.active) {
                rows.value = [...rows.value, created].sort((a, b) => (a.name || '').localeCompare(b.name || ''));
            }
            return created;
        } catch (e) {
            error.value = e?.message || 'Falha ao criar convênio.';
            throw e;
        } finally {
            loading.value = false;
        }
    }

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

    async function softDelete(id, opts = {}) {
        loading.value = true;
        error.value = '';
        try {
            await repoSoftDelete(id, opts);
            rows.value = rows.value.filter((r) => r.id !== id);
            return true;
        } catch (e) {
            error.value = e?.message || 'Falha ao remover convênio.';
            throw e;
        } finally {
            loading.value = false;
        }
    }

    return { rows, loading, error, loadForOwner, fetchById, findByName, create, update, softDelete };
}
