-- ============================================================
  -- LIMPEZA DE DADOS DE TESTE — filtra por tenant/owner
  -- Execute no Supabase Studio com cuidado                                                                               -- ============================================================
  DO $$                                                                                                                   DECLARE
    v_tenant_id  uuid := 'bbbbbbbb-0002-0002-0002-000000000002';
    v_owner_id   uuid := 'aaaaaaaa-0002-0002-0002-000000000002';
    n_exc   int;
    n_ev    int;
    n_rule  int;
    n_sol   int;
  BEGIN

    -- 1. Exceções (filha de recurrence_rules — apagar primeiro)
    DELETE FROM public.recurrence_exceptions
    WHERE recurrence_id IN (
      SELECT id FROM public.recurrence_rules
      WHERE (v_tenant_id IS NULL OR tenant_id = v_tenant_id)
        AND (v_owner_id  IS NULL OR owner_id  = v_owner_id)
    );
    GET DIAGNOSTICS n_exc = ROW_COUNT;

    -- 2. Regras de recorrência
    DELETE FROM public.recurrence_rules
    WHERE (v_tenant_id IS NULL OR tenant_id = v_tenant_id)
      AND (v_owner_id  IS NULL OR owner_id  = v_owner_id);
    GET DIAGNOSTICS n_rule = ROW_COUNT;

    -- 3. Eventos da agenda
    DELETE FROM public.agenda_eventos
    WHERE (v_tenant_id IS NULL OR tenant_id = v_tenant_id)
      AND (v_owner_id  IS NULL OR owner_id  = v_owner_id);
    GET DIAGNOSTICS n_ev = ROW_COUNT;

    -- 4. Solicitações públicas (agendador online)
    DELETE FROM public.agendador_solicitacoes
    WHERE (v_tenant_id IS NULL OR tenant_id = v_tenant_id)
      AND (v_owner_id  IS NULL OR owner_id  = v_owner_id);
    GET DIAGNOSTICS n_sol = ROW_COUNT;

    RAISE NOTICE '✅ Limpeza concluída:';
    RAISE NOTICE '   recurrence_exceptions  : %', n_exc;
    RAISE NOTICE '   recurrence_rules       : %', n_rule;
    RAISE NOTICE '   agenda_eventos         : %', n_ev;
    RAISE NOTICE '   agendador_solicitacoes : %', n_sol;
  END;
  $$;
