/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/patients/composables/usePatients.js
|
| Thin wrapper sobre patientsRepository (composable-blueprint Tipo A).
| Toda I/O delegada ao repository. State reativo: rows, loading, error.
| Mutations re-throw após registrar error.value pra caller decidir UX.
|--------------------------------------------------------------------------
*/
import { ref } from 'vue';
import {
    listPatients,
    getPatientById,
    createPatient,
    updatePatient,
    softDeletePatient
} from '@/features/patients/services/patientsRepository';

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

    async function load(opts) {
        loading.value = true;
        error.value = '';
        try {
            rows.value = await listPatients(opts);
        } catch (e) {
            error.value = e?.message || 'Erro ao carregar pacientes';
            rows.value = [];
        } finally {
            loading.value = false;
        }
    }

    async function getById(id, opts) {
        loading.value = true;
        error.value = '';
        try {
            return await getPatientById(id, opts);
        } catch (e) {
            error.value = e?.message || 'Erro ao carregar paciente';
            return null;
        } finally {
            loading.value = false;
        }
    }

    async function create(payload) {
        loading.value = true;
        error.value = '';
        try {
            return await createPatient(payload);
        } catch (e) {
            error.value = e?.message || 'Erro ao criar paciente';
            throw e;
        } finally {
            loading.value = false;
        }
    }

    async function update(id, patch, opts) {
        loading.value = true;
        error.value = '';
        try {
            return await updatePatient(id, patch, opts);
        } catch (e) {
            error.value = e?.message || 'Erro ao atualizar paciente';
            throw e;
        } finally {
            loading.value = false;
        }
    }

    async function remove(id, opts) {
        loading.value = true;
        error.value = '';
        try {
            await softDeletePatient(id, opts);
        } catch (e) {
            error.value = e?.message || 'Erro ao remover paciente';
            throw e;
        } finally {
            loading.value = false;
        }
    }

    return { rows, loading, error, load, getById, create, update, remove };
}
