/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/services/patientTags.service.js
| Data: 2026
| Local: São Carlos/SP — Brasil
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
*/
import { supabase } from '@/lib/supabase/client';

import { tenantDb } from '@/lib/supabase/tenantClient';
async function getOwnerId() {
    const { data, error } = await supabase.auth.getUser();
    if (error) throw error;
    const user = data?.user;
    if (!user) throw new Error('Você precisa estar logado.');
    return user.id;
}

export async function listTagsWithCounts() {
    const ownerId = await getOwnerId();
    const v = await tenantDb().from('v_tag_patient_counts').select('*').eq('owner_id', ownerId).order('name', { ascending: true });

    if (!v.error) return v.data || [];

    const t = await tenantDb().from('patient_tags').select('id, owner_id, name, color, is_native, created_at, updated_at').eq('owner_id', ownerId).order('name', { ascending: true });

    if (t.error) throw t.error;
    return (t.data || []).map((r) => ({ ...r, patient_count: 0 }));
}

export async function createTag({ name, color = null }) {
    const ownerId = await getOwnerId();
    const { error } = await tenantDb().from('patient_tags').insert({ owner_id: ownerId, name, color });
    if (error) throw error;
}

export async function updateTag({ id, name, color = null }) {
    const ownerId = await getOwnerId();
    const { error } = await tenantDb().from('patient_tags').update({ name, color, updated_at: new Date().toISOString() }).eq('id', id).eq('owner_id', ownerId);
    if (error) throw error;
}

export async function deleteTagsByIds(ids = []) {
    const ownerId = await getOwnerId();
    if (!ids.length) return;

    const pivotDel = await tenantDb().from('patient_patient_tag').delete().eq('owner_id', ownerId).in('tag_id', ids);
    if (pivotDel.error) throw pivotDel.error;

    const tagDel = await tenantDb().from('patient_tags').delete().eq('owner_id', ownerId).in('id', ids);
    if (tagDel.error) throw tagDel.error;
}

export async function fetchPatientsByTagId(tagId) {
    const ownerId = await getOwnerId();
    const { data, error } = await tenantDb().from('patient_patient_tag').select('patient_id, patients:patients(id, name, email, phone)').eq('owner_id', ownerId).eq('tag_id', tagId);

    if (error) throw error;
    return (data || []).map((r) => r.patients).filter(Boolean);
}
