-- =============================================================================
-- FIX: Atribuir plano free a usuários/tenants sem assinatura ativa
-- =============================================================================
-- Execute no SQL Editor do Supabase (service_role)
-- Idempotente: só insere onde não existe assinatura ativa.
--
-- Regras:
--   • tenant kind = 'therapist'                       → therapist_free (por user_id do admin)
--   • tenant kind IN (clinic_*)                       → clinic_free    (por tenant_id)
--   • profiles.account_type = 'patient' / portal_user → patient_free   (por user_id)
-- =============================================================================

BEGIN;

-- ──────────────────────────────────────────────────────────────────────────────
-- DIAGNÓSTICO — mostra o estado atual antes de corrigir
-- ──────────────────────────────────────────────────────────────────────────────

DO $$
DECLARE
  r RECORD;
BEGIN
  RAISE NOTICE '=== DIAGNÓSTICO DE ASSINATURAS ===';
  RAISE NOTICE '';

  -- Terapeutas sem plano
  RAISE NOTICE '--- Terapeutas SEM assinatura ativa ---';
  FOR r IN
    SELECT
      tm.user_id,
      p.full_name,
      t.id AS tenant_id,
      t.name AS tenant_name
    FROM public.tenant_members tm
    JOIN public.tenants t ON t.id = tm.tenant_id
    JOIN public.profiles p ON p.id = tm.user_id
    WHERE t.kind = 'therapist'
      AND tm.role = 'tenant_admin'
      AND tm.status = 'active'
      AND NOT EXISTS (
        SELECT 1 FROM public.subscriptions s
        WHERE s.user_id = tm.user_id
          AND s.status = 'active'
      )
  LOOP
    RAISE NOTICE '  FALTANDO: % (%) — tenant %', r.full_name, r.user_id, r.tenant_id;
  END LOOP;

  -- Clínicas sem plano
  RAISE NOTICE '';
  RAISE NOTICE '--- Clínicas SEM assinatura ativa ---';
  FOR r IN
    SELECT t.id, t.name, t.kind
    FROM public.tenants t
    WHERE t.kind IN ('clinic_coworking', 'clinic_reception', 'clinic_full', 'clinic')
      AND NOT EXISTS (
        SELECT 1 FROM public.subscriptions s
        WHERE s.tenant_id = t.id
          AND s.status = 'active'
      )
  LOOP
    RAISE NOTICE '  FALTANDO: % (%) — kind %', r.name, r.id, r.kind;
  END LOOP;

  -- Pacientes sem plano
  RAISE NOTICE '';
  RAISE NOTICE '--- Pacientes SEM assinatura ativa ---';
  FOR r IN
    SELECT p.id, p.full_name
    FROM public.profiles p
    WHERE p.account_type = 'patient'
      AND NOT EXISTS (
        SELECT 1 FROM public.subscriptions s
        WHERE s.user_id = p.id
          AND s.status = 'active'
      )
  LOOP
    RAISE NOTICE '  FALTANDO: % (%)', r.full_name, r.id;
  END LOOP;

  RAISE NOTICE '';
  RAISE NOTICE '=== FIM DO DIAGNÓSTICO — aplicando correções... ===';
END;
$$;


-- ──────────────────────────────────────────────────────────────────────────────
-- CORREÇÃO 1: Terapeutas sem assinatura → therapist_free
-- Escopo: user_id do tenant_admin do tenant kind='therapist'
-- ──────────────────────────────────────────────────────────────────────────────

INSERT INTO public.subscriptions (
  user_id, plan_id, plan_key, status, interval,
  current_period_start, current_period_end,
  source, started_at, activated_at
)
SELECT
  tm.user_id,
  p.id,
  p.key,
  'active',
  'month',
  now(),
  now() + interval '30 days',
  'fix_seed',
  now(),
  now()
FROM public.tenant_members tm
JOIN public.tenants t   ON t.id = tm.tenant_id
JOIN public.plans   p   ON p.key = 'therapist_free'
WHERE t.kind = 'therapist'
  AND tm.role = 'tenant_admin'
  AND tm.status = 'active'
  AND NOT EXISTS (
    SELECT 1 FROM public.subscriptions s
    WHERE s.user_id = tm.user_id
      AND s.status = 'active'
  );


-- ──────────────────────────────────────────────────────────────────────────────
-- CORREÇÃO 2: Clínicas sem assinatura → clinic_free
-- Escopo: tenant_id
-- ──────────────────────────────────────────────────────────────────────────────

INSERT INTO public.subscriptions (
  tenant_id, plan_id, plan_key, status, interval,
  current_period_start, current_period_end,
  source, started_at, activated_at
)
SELECT
  t.id,
  p.id,
  p.key,
  'active',
  'month',
  now(),
  now() + interval '30 days',
  'fix_seed',
  now(),
  now()
FROM public.tenants t
JOIN public.plans   p ON p.key = 'clinic_free'
WHERE t.kind IN ('clinic_coworking', 'clinic_reception', 'clinic_full', 'clinic')
  AND NOT EXISTS (
    SELECT 1 FROM public.subscriptions s
    WHERE s.tenant_id = t.id
      AND s.status = 'active'
  );


-- ──────────────────────────────────────────────────────────────────────────────
-- CORREÇÃO 3: Pacientes sem assinatura → patient_free
-- Escopo: user_id
-- ──────────────────────────────────────────────────────────────────────────────

INSERT INTO public.subscriptions (
  user_id, plan_id, plan_key, status, interval,
  current_period_start, current_period_end,
  source, started_at, activated_at
)
SELECT
  pr.id,
  p.id,
  p.key,
  'active',
  'month',
  now(),
  now() + interval '30 days',
  'fix_seed',
  now(),
  now()
FROM public.profiles pr
JOIN public.plans    p  ON p.key = 'patient_free'
WHERE pr.account_type = 'patient'
  AND NOT EXISTS (
    SELECT 1 FROM public.subscriptions s
    WHERE s.user_id = pr.id
      AND s.status = 'active'
  );


-- ──────────────────────────────────────────────────────────────────────────────
-- CONFIRMAÇÃO — mostra o que foi inserido (source = 'fix_seed')
-- ──────────────────────────────────────────────────────────────────────────────

DO $$
DECLARE
  r RECORD;
  total INT := 0;
BEGIN
  RAISE NOTICE '';
  RAISE NOTICE '=== ASSINATURAS CRIADAS NESTA EXECUÇÃO ===';

  FOR r IN
    SELECT
      s.plan_key,
      COALESCE(pr.full_name, t.name) AS nome,
      COALESCE(s.user_id::text, s.tenant_id::text) AS owner_id
    FROM public.subscriptions s
    LEFT JOIN public.profiles pr ON pr.id = s.user_id
    LEFT JOIN public.tenants   t  ON t.id  = s.tenant_id
    WHERE s.source = 'fix_seed'
      AND s.started_at >= now() - interval '5 seconds'
    ORDER BY s.plan_key, nome
  LOOP
    RAISE NOTICE '  ✅ % → % (%)', r.plan_key, r.nome, r.owner_id;
    total := total + 1;
  END LOOP;

  IF total = 0 THEN
    RAISE NOTICE '  (nenhuma nova assinatura criada — todos já tinham plano ativo)';
  ELSE
    RAISE NOTICE '';
    RAISE NOTICE '  Total: % assinatura(s) criada(s).', total;
  END IF;
END;
$$;

COMMIT;
