/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/patients/prontuario/composables/useClinicalNoteTemplates.js
|
| Thin wrapper sobre clinicalNoteTemplatesRepository.
| Carrega templates visíveis (sistema + tenant + owner), filtra por noteType.
|
| ⚠️ Depende das migrations 0.5.B + seed_040_clinical_note_templates.sql.
|--------------------------------------------------------------------------
*/
import { ref, computed } from 'vue';
import {
    listAvailable,
    getById,
    getByKey,
    create as repoCreate,
    update as repoUpdate,
    softDelete as repoSoftDelete
} from '@/features/patients/prontuario/services/clinicalNoteTemplatesRepository';

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

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

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

    async function fetchByKey(key, opts = {}) {
        try {
            return await getByKey(key, opts);
        } catch (e) {
            error.value = e?.message || 'Falha ao carregar template.';
            return null;
        }
    }

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

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

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

    // ─── Computeds derivados ────────────────────────────────────────────

    const systemTemplates = computed(() => rows.value.filter((t) => t.is_system));
    const tenantTemplates = computed(() => rows.value.filter((t) => !t.is_system && t.tenant_id && !t.owner_id));
    const ownerTemplates = computed(() => rows.value.filter((t) => !t.is_system && t.owner_id));

    function byType(noteType) {
        return rows.value.filter((t) => t.note_type === noteType);
    }

    return {
        rows,
        loading,
        error,
        load,
        fetchById,
        fetchByKey,
        create,
        update,
        softDelete,
        systemTemplates,
        tenantTemplates,
        ownerTemplates,
        byType
    };
}
