-- =============================================================================
-- SEED 003 — Terapeuta 2, Terapeuta 3 e Secretária
-- =============================================================================
-- Execute APÓS seed_001.sql (e seed_002.sql se quiser todos os seeds)
-- Requer: pgcrypto (já ativo no Supabase)
--
-- Cria os seguintes usuários de teste:
--
--   therapist2@agenciapsi.com.br  senha: Teste@123  → terapeuta 2 (tenant próprio + Clínica 3)
--   therapist3@agenciapsi.com.br  senha: Teste@123  → terapeuta 3 (tenant próprio + Clínica 3)
--   secretary@agenciapsi.com.br   senha: Teste@123  → clinic_admin na Clínica 2 (Mente sã)
--
-- UUIDs reservados:
--   Terapeuta 2  → aaaaaaaa-0009-0009-0009-000000000009
--   Terapeuta 3  → aaaaaaaa-0010-0010-0010-000000000010
--   Secretária   → aaaaaaaa-0011-0011-0011-000000000011
-- Tenant Terapeuta 2 → bbbbbbbb-0009-0009-0009-000000000009
-- Tenant Terapeuta 3 → bbbbbbbb-0010-0010-0010-000000000010
-- =============================================================================

BEGIN;

-- ============================================================
-- 1. Remove seeds anteriores (idempotente)
-- ============================================================

DELETE FROM auth.users
WHERE email IN (
  'therapist2@agenciapsi.com.br',
  'therapist3@agenciapsi.com.br',
  'secretary@agenciapsi.com.br'
);


-- ============================================================
-- 2. Cria usuários no auth.users
-- ⚠️  confirmed_at é coluna gerada — NÃO incluir na lista
-- ============================================================

INSERT INTO auth.users (
  instance_id,
  id,
  email,
  encrypted_password,
  email_confirmed_at,
  created_at,
  updated_at,
  raw_user_meta_data,
  raw_app_meta_data,
  role,
  aud,
  is_sso_user,
  is_anonymous,
  confirmation_token,
  recovery_token,
  email_change_token_new,
  email_change_token_current,
  email_change
)
VALUES
  -- Terapeuta 2
  (
    '00000000-0000-0000-0000-000000000000',
    'aaaaaaaa-0009-0009-0009-000000000009',
    'therapist2@agenciapsi.com.br',
    crypt('Teste@123', gen_salt('bf')),
    now(), now(), now(),
    '{"name": "Eva Terapeuta"}'::jsonb,
    '{"provider": "email", "providers": ["email"]}'::jsonb,
    'authenticated', 'authenticated', false, false, '', '', '', '', ''
  ),
  -- Terapeuta 3
  (
    '00000000-0000-0000-0000-000000000000',
    'aaaaaaaa-0010-0010-0010-000000000010',
    'therapist3@agenciapsi.com.br',
    crypt('Teste@123', gen_salt('bf')),
    now(), now(), now(),
    '{"name": "Felipe Terapeuta"}'::jsonb,
    '{"provider": "email", "providers": ["email"]}'::jsonb,
    'authenticated', 'authenticated', false, false, '', '', '', '', ''
  ),
  -- Secretária
  (
    '00000000-0000-0000-0000-000000000000',
    'aaaaaaaa-0011-0011-0011-000000000011',
    'secretary@agenciapsi.com.br',
    crypt('Teste@123', gen_salt('bf')),
    now(), now(), now(),
    '{"name": "Gabriela Secretária"}'::jsonb,
    '{"provider": "email", "providers": ["email"]}'::jsonb,
    'authenticated', 'authenticated', false, false, '', '', '', '', ''
  );


-- ============================================================
-- 3. auth.identities (obrigatório para GoTrue reconhecer login)
-- ============================================================

INSERT INTO auth.identities (id, user_id, provider_id, provider, identity_data, created_at, updated_at, last_sign_in_at)
VALUES
  (
    gen_random_uuid(),
    'aaaaaaaa-0009-0009-0009-000000000009',
    'therapist2@agenciapsi.com.br',
    'email',
    '{"sub": "aaaaaaaa-0009-0009-0009-000000000009", "email": "therapist2@agenciapsi.com.br", "email_verified": true}'::jsonb,
    now(), now(), now()
  ),
  (
    gen_random_uuid(),
    'aaaaaaaa-0010-0010-0010-000000000010',
    'therapist3@agenciapsi.com.br',
    'email',
    '{"sub": "aaaaaaaa-0010-0010-0010-000000000010", "email": "therapist3@agenciapsi.com.br", "email_verified": true}'::jsonb,
    now(), now(), now()
  ),
  (
    gen_random_uuid(),
    'aaaaaaaa-0011-0011-0011-000000000011',
    'secretary@agenciapsi.com.br',
    'email',
    '{"sub": "aaaaaaaa-0011-0011-0011-000000000011", "email": "secretary@agenciapsi.com.br", "email_verified": true}'::jsonb,
    now(), now(), now()
  )
ON CONFLICT (provider, provider_id) DO NOTHING;


-- ============================================================
-- 4. Profiles
-- ============================================================

INSERT INTO public.profiles (id, role, account_type, full_name)
VALUES
  (
    'aaaaaaaa-0009-0009-0009-000000000009',
    'tenant_member',
    'therapist',
    'Eva Terapeuta'
  ),
  (
    'aaaaaaaa-0010-0010-0010-000000000010',
    'tenant_member',
    'therapist',
    'Felipe Terapeuta'
  ),
  (
    'aaaaaaaa-0011-0011-0011-000000000011',
    'tenant_member',
    'therapist',
    'Gabriela Secretária'
  )
ON CONFLICT (id) DO UPDATE SET
  role         = EXCLUDED.role,
  account_type = EXCLUDED.account_type,
  full_name    = EXCLUDED.full_name;


-- ============================================================
-- 5. Tenants pessoais dos Terapeutas 2 e 3
-- ============================================================

INSERT INTO public.tenants (id, name, kind, created_at)
VALUES
  ('bbbbbbbb-0009-0009-0009-000000000009', 'Eva Terapeuta',    'therapist', now()),
  ('bbbbbbbb-0010-0010-0010-000000000010', 'Felipe Terapeuta', 'therapist', now())
ON CONFLICT (id) DO NOTHING;

-- Terapeuta 2 → tenant_admin do próprio tenant
INSERT INTO public.tenant_members (tenant_id, user_id, role, status, created_at)
VALUES (
  'bbbbbbbb-0009-0009-0009-000000000009',
  'aaaaaaaa-0009-0009-0009-000000000009',
  'tenant_admin', 'active', now()
)
ON CONFLICT (tenant_id, user_id) DO NOTHING;

-- Terapeuta 3 → tenant_admin do próprio tenant
INSERT INTO public.tenant_members (tenant_id, user_id, role, status, created_at)
VALUES (
  'bbbbbbbb-0010-0010-0010-000000000010',
  'aaaaaaaa-0010-0010-0010-000000000010',
  'tenant_admin', 'active', now()
)
ON CONFLICT (tenant_id, user_id) DO NOTHING;


-- ============================================================
-- 6. Vincula Terapeutas 2 e 3 à Clínica 3 — Full
--    (mesmo padrão de terapeuta@agenciapsi.com.br no seed_001)
-- ============================================================

INSERT INTO public.tenant_members (tenant_id, user_id, role, status, created_at)
VALUES
  (
    'bbbbbbbb-0005-0005-0005-000000000005',  -- Clínica Bem Estar (Full)
    'aaaaaaaa-0009-0009-0009-000000000009',  -- Eva Terapeuta
    'therapist', 'active', now()
  ),
  (
    'bbbbbbbb-0005-0005-0005-000000000005',  -- Clínica Bem Estar (Full)
    'aaaaaaaa-0010-0010-0010-000000000010',  -- Felipe Terapeuta
    'therapist', 'active', now()
  )
ON CONFLICT (tenant_id, user_id) DO NOTHING;


-- ============================================================
-- 7. Vincula Secretária à Clínica 2 (Recepção) como clinic_admin
--    A secretária gerencia a recepção/agenda da clínica.
--    Acessa a área /admin com o mesmo contexto de clinic_admin.
-- ============================================================

INSERT INTO public.tenant_members (tenant_id, user_id, role, status, created_at)
VALUES (
  'bbbbbbbb-0004-0004-0004-000000000004',  -- Clínica Mente sã (Recepção)
  'aaaaaaaa-0011-0011-0011-000000000011',  -- Gabriela Secretária
  'clinic_admin', 'active', now()
)
ON CONFLICT (tenant_id, user_id) DO NOTHING;


-- ============================================================
-- 8. Subscriptions
--    Terapeutas 2 e 3 → therapist_free (escopo: user_id)
--    Secretária       → sem assinatura própria (usa o plano da Clínica 2)
-- ============================================================

-- Terapeuta 2 → therapist_free
INSERT INTO public.subscriptions (
  user_id, plan_id, plan_key, status, interval,
  current_period_start, current_period_end,
  source, started_at, activated_at
)
SELECT
  'aaaaaaaa-0009-0009-0009-000000000009',
  p.id, p.key, 'active', 'month',
  now(), now() + interval '30 days',
  'seed', now(), now()
FROM public.plans p WHERE p.key = 'therapist_free'
AND NOT EXISTS (
  SELECT 1 FROM public.subscriptions s
  WHERE s.user_id = 'aaaaaaaa-0009-0009-0009-000000000009' AND s.status = 'active'
);

-- Terapeuta 3 → therapist_free
INSERT INTO public.subscriptions (
  user_id, plan_id, plan_key, status, interval,
  current_period_start, current_period_end,
  source, started_at, activated_at
)
SELECT
  'aaaaaaaa-0010-0010-0010-000000000010',
  p.id, p.key, 'active', 'month',
  now(), now() + interval '30 days',
  'seed', now(), now()
FROM public.plans p WHERE p.key = 'therapist_free'
AND NOT EXISTS (
  SELECT 1 FROM public.subscriptions s
  WHERE s.user_id = 'aaaaaaaa-0010-0010-0010-000000000010' AND s.status = 'active'
);

-- Nota: a Secretária não tem assinatura própria.
-- O acesso vem do plano da Clínica 2 (tenant_id = bbbbbbbb-0004-0004-0004-000000000004).


-- ============================================================
-- 9. Confirma
-- ============================================================

DO $$
BEGIN
  RAISE NOTICE '✅ Seed 003 aplicado com sucesso.';
  RAISE NOTICE '';
  RAISE NOTICE '  Usuários criados:';
  RAISE NOTICE '  therapist2@agenciapsi.com.br  → tenant próprio (bbbbbbbb-0009) + Clínica 3 como therapist';
  RAISE NOTICE '  therapist3@agenciapsi.com.br  → tenant próprio (bbbbbbbb-0010) + Clínica 3 como therapist';
  RAISE NOTICE '  secretary@agenciapsi.com.br   → clinic_admin na Clínica 2 Mente sã (bbbbbbbb-0004)';
  RAISE NOTICE '  Senha de todos: Teste@123';
END;
$$;

COMMIT;
