-- ============================================================
-- Fix: cria função seed_default_patient_groups
-- Colunas reais: nome, cor, descricao, tenant_id (NOT NULL)
-- ============================================================

CREATE OR REPLACE FUNCTION public.seed_default_patient_groups(p_tenant_id uuid)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  v_owner_id uuid;
BEGIN
  -- busca o owner (tenant_admin) do tenant
  SELECT user_id INTO v_owner_id
  FROM public.tenant_members
  WHERE tenant_id = p_tenant_id
    AND role = 'tenant_admin'
    AND status = 'active'
  LIMIT 1;

  IF v_owner_id IS NULL THEN
    RETURN;
  END IF;

  INSERT INTO public.patient_groups (owner_id, nome, cor, is_system, tenant_id)
  VALUES
    (v_owner_id, 'Crianças',     '#60a5fa', true, p_tenant_id),
    (v_owner_id, 'Adolescentes', '#a78bfa', true, p_tenant_id),
    (v_owner_id, 'Idosos',       '#34d399', true, p_tenant_id)
  ON CONFLICT (owner_id, nome) DO NOTHING;
END;
$$;

GRANT EXECUTE ON FUNCTION public.seed_default_patient_groups(uuid)
  TO postgres, anon, authenticated, service_role;
