-- =============================================================================
-- Migration: 20260419000009_patient_session_counts_rpc
-- V#8 — Substitui o .limit(1000) arbitrário em PatientsListPage por RPC
-- agregada que retorna contagens por paciente (sempre atualizada, sem teto).
--
-- Tenant scoping é feito via WHERE tenant_id IN (memberships do caller),
-- consistente com a policy SELECT de agenda_eventos.
-- =============================================================================

CREATE OR REPLACE FUNCTION public.get_patient_session_counts(
    p_patient_ids uuid[]
)
RETURNS TABLE(patient_id uuid, session_count integer, last_session_at timestamptz)
LANGUAGE sql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
    SELECT
        ae.patient_id,
        COUNT(*)::int                AS session_count,
        MAX(ae.inicio_em)            AS last_session_at
    FROM public.agenda_eventos ae
    WHERE ae.patient_id = ANY(p_patient_ids)
      AND ae.tenant_id IN (
          SELECT tm.tenant_id
          FROM public.tenant_members tm
          WHERE tm.user_id = auth.uid()
            AND tm.status = 'active'
      )
    GROUP BY ae.patient_id;
$function$;

REVOKE ALL ON FUNCTION public.get_patient_session_counts(uuid[]) FROM PUBLIC, anon;
GRANT  EXECUTE ON FUNCTION public.get_patient_session_counts(uuid[]) TO authenticated;
