-- ============================================================
-- CLEANUP — Remove TODOS os dados de seed/teste
-- AgenciaPsi — 2026-03-22
-- ============================================================
-- Remove dados criados por seed_test_data.sql:
--   - 10 terapeutas fictícios (aaaaaaaa-*)
--   - 10 tenants fictícios (bbbbbbbb-*)
--   - 50 pacientes fictícios (cccccccc-*)
--   - Eventos, financeiro, grupos, recorrências
--   - Dados seed do terapeuta@agenciapsi.com.br ([SEED])
--   - Notification queue/logs dos tenants de teste
--   - Addon credits/transactions dos tenants de teste
--
-- SEGURO: Não apaga dados reais (apenas UUIDs/emails conhecidos)
-- ============================================================

DO $$
DECLARE
  _tenant_ids uuid[] := ARRAY[
    'bbbbbbbb-0000-0000-0000-000000000001'::uuid,
    'bbbbbbbb-0000-0000-0000-000000000002'::uuid,
    'bbbbbbbb-0000-0000-0000-000000000003'::uuid,
    'bbbbbbbb-0000-0000-0000-000000000004'::uuid,
    'bbbbbbbb-0000-0000-0000-000000000005'::uuid,
    'bbbbbbbb-0000-0000-0000-000000000006'::uuid,
    'bbbbbbbb-0000-0000-0000-000000000007'::uuid,
    'bbbbbbbb-0000-0000-0000-000000000008'::uuid,
    'bbbbbbbb-0000-0000-0000-000000000009'::uuid,
    'bbbbbbbb-0000-0000-0000-000000000010'::uuid
  ];
  _user_ids uuid[] := ARRAY[
    'aaaaaaaa-0000-0000-0000-000000000001'::uuid,
    'aaaaaaaa-0000-0000-0000-000000000002'::uuid,
    'aaaaaaaa-0000-0000-0000-000000000003'::uuid,
    'aaaaaaaa-0000-0000-0000-000000000004'::uuid,
    'aaaaaaaa-0000-0000-0000-000000000005'::uuid,
    'aaaaaaaa-0000-0000-0000-000000000006'::uuid,
    'aaaaaaaa-0000-0000-0000-000000000007'::uuid,
    'aaaaaaaa-0000-0000-0000-000000000008'::uuid,
    'aaaaaaaa-0000-0000-0000-000000000009'::uuid,
    'aaaaaaaa-0000-0000-0000-000000000010'::uuid
  ];
  _real_oid uuid;
  _real_tid uuid;
  _deleted int;
  _total int := 0;
BEGIN
  RAISE NOTICE '══════════════════════════════════════════';
  RAISE NOTICE '  CLEANUP — Removendo dados de teste...';
  RAISE NOTICE '══════════════════════════════════════════';

  -- ── Notification queue e logs (tenants fictícios) ──────────
  DELETE FROM public.notification_logs WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  notification_logs:        % removidos', _deleted;

  DELETE FROM public.notification_queue WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  notification_queue:       % removidos', _deleted;

  DELETE FROM public.notification_preferences WHERE owner_id = ANY(_user_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  notification_preferences: % removidos', _deleted;

  DELETE FROM public.notification_schedules WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  notification_schedules:   % removidos', _deleted;

  DELETE FROM public.notification_channels WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  notification_channels:    % removidos', _deleted;

  DELETE FROM public.notification_templates WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  notification_templates:   % removidos', _deleted;

  -- ── Addon credits/transactions (tenants fictícios) ─────────
  IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'addon_transactions') THEN
    DELETE FROM public.addon_transactions WHERE tenant_id = ANY(_tenant_ids);
    GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
    RAISE NOTICE '  addon_transactions:      % removidos', _deleted;
  END IF;

  IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'addon_credits') THEN
    DELETE FROM public.addon_credits WHERE tenant_id = ANY(_tenant_ids);
    GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
    RAISE NOTICE '  addon_credits:           % removidos', _deleted;
  END IF;

  -- ── Financeiro ─────────────────────────────────────────────
  DELETE FROM public.financial_records WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  financial_records:        % removidos', _deleted;

  -- ── Eventos agenda ─────────────────────────────────────────
  DELETE FROM public.agenda_eventos WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  agenda_eventos:           % removidos', _deleted;

  -- ── Recorrências ───────────────────────────────────────────
  DELETE FROM public.recurrence_rules WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  recurrence_rules:         % removidos', _deleted;

  -- ── Grupos ─────────────────────────────────────────────────
  DELETE FROM public.patient_group_patient WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  patient_group_patient:    % removidos', _deleted;

  DELETE FROM public.patient_groups WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  patient_groups:           % removidos', _deleted;

  -- ── Pacientes ──────────────────────────────────────────────
  DELETE FROM public.patients WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  patients:                 % removidos', _deleted;

  -- ── Regras semanais ────────────────────────────────────────
  DELETE FROM public.agenda_regras_semanais WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  agenda_regras_semanais:   % removidos', _deleted;

  -- ── Serviços ───────────────────────────────────────────────
  DELETE FROM public.services WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  services:                 % removidos', _deleted;

  -- ── Tenant members ─────────────────────────────────────────
  DELETE FROM public.tenant_members WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  tenant_members:           % removidos', _deleted;

  -- ── Company profiles ───────────────────────────────────────
  DELETE FROM public.company_profiles WHERE tenant_id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  company_profiles:         % removidos', _deleted;

  -- ── Tenants ────────────────────────────────────────────────
  DELETE FROM public.tenants WHERE id = ANY(_tenant_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  tenants:                  % removidos', _deleted;

  -- ── Profiles ───────────────────────────────────────────────
  DELETE FROM public.profiles WHERE id = ANY(_user_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  profiles:                 % removidos', _deleted;

  -- ── Auth users ─────────────────────────────────────────────
  ALTER TABLE auth.users DISABLE TRIGGER ALL;
  DELETE FROM auth.identities WHERE user_id = ANY(_user_ids);
  DELETE FROM auth.users WHERE id = ANY(_user_ids);
  GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
  RAISE NOTICE '  auth.users:               % removidos', _deleted;
  ALTER TABLE auth.users ENABLE TRIGGER ALL;

  -- ══════════════════════════════════════════════════════════
  -- DADOS [SEED] DO terapeuta@agenciapsi.com.br
  -- ══════════════════════════════════════════════════════════
  SELECT id INTO _real_oid FROM auth.users WHERE email = 'terapeuta@agenciapsi.com.br';

  IF _real_oid IS NOT NULL THEN
    SELECT t.id INTO _real_tid
    FROM public.tenants t
    JOIN public.tenant_members tm ON tm.tenant_id = t.id
    WHERE tm.user_id = _real_oid
    LIMIT 1;

    IF _real_tid IS NOT NULL THEN
      RAISE NOTICE '';
      RAISE NOTICE '  Limpando [SEED] de terapeuta@agenciapsi.com.br...';

      -- Notification queue/logs deste tenant (apenas os de teste)
      DELETE FROM public.notification_logs WHERE tenant_id = _real_tid
        AND queue_id IN (SELECT id FROM public.notification_queue WHERE tenant_id = _real_tid);
      GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
      RAISE NOTICE '  notification_logs (real): % removidos', _deleted;

      DELETE FROM public.notification_queue WHERE tenant_id = _real_tid;
      GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
      RAISE NOTICE '  notification_queue (real):% removidos', _deleted;

      -- Financeiro [SEED]
      DELETE FROM public.financial_records WHERE tenant_id = _real_tid AND description LIKE '[SEED]%';
      GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
      RAISE NOTICE '  financial_records [SEED]: % removidos', _deleted;

      -- Eventos [SEED]
      DELETE FROM public.agenda_eventos WHERE tenant_id = _real_tid AND titulo LIKE '[SEED]%';
      GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
      RAISE NOTICE '  agenda_eventos [SEED]:    % removidos', _deleted;

      -- Recorrências [SEED]
      DELETE FROM public.recurrence_rules WHERE tenant_id = _real_tid AND observacoes = '[SEED]';
      GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
      RAISE NOTICE '  recurrence_rules [SEED]:  % removidos', _deleted;

      -- Grupos [SEED]
      DELETE FROM public.patient_group_patient WHERE tenant_id = _real_tid AND patient_id IN (
        SELECT id FROM public.patients WHERE tenant_id = _real_tid AND email_principal LIKE '%@seed.teste.agenciapsi.com'
      );
      GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
      RAISE NOTICE '  group_patient [SEED]:     % removidos', _deleted;

      DELETE FROM public.patient_groups WHERE tenant_id = _real_tid AND nome LIKE '%[SEED]%';
      GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
      RAISE NOTICE '  patient_groups [SEED]:    % removidos', _deleted;

      -- Pacientes seed
      DELETE FROM public.patients WHERE tenant_id = _real_tid AND email_principal LIKE '%@seed.teste.agenciapsi.com';
      GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
      RAISE NOTICE '  patients [SEED]:          % removidos', _deleted;

      -- Regras semanais e schedules (reseta tudo deste owner)
      DELETE FROM public.agenda_regras_semanais WHERE tenant_id = _real_tid AND owner_id = _real_oid;
      GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
      RAISE NOTICE '  regras_semanais (real):   % removidos', _deleted;

      DELETE FROM public.notification_schedules WHERE tenant_id = _real_tid AND owner_id = _real_oid;
      GET DIAGNOSTICS _deleted = ROW_COUNT; _total := _total + _deleted;
      RAISE NOTICE '  notif_schedules (real):   % removidos', _deleted;
    END IF;
  ELSE
    RAISE NOTICE '  terapeuta@agenciapsi.com.br não encontrado — pulando';
  END IF;

  RAISE NOTICE '';
  RAISE NOTICE '══════════════════════════════════════════';
  RAISE NOTICE '  CLEANUP COMPLETO — % registros removidos', _total;
  RAISE NOTICE '══════════════════════════════════════════';
END $$;
