-- =============================================================================
-- SEED — Usuários fictícios para teste
-- =============================================================================
-- IMPORTANTE: Execute APÓS a migration_001.sql
-- IMPORTANTE: Requer extensão pgcrypto (já ativa no Supabase)
--
-- Cria os seguintes usuários de teste:
--
--   paciente@agenciapsi.com.br       senha: Teste@123  → paciente
--   terapeuta@agenciapsi.com.br      senha: Teste@123  → terapeuta solo
--   clinica1@agenciapsi.com.br       senha: Teste@123  → clínica coworking
--   clinica2@agenciapsi.com.br       senha: Teste@123  → clínica com secretaria
--   clinica3@agenciapsi.com.br       senha: Teste@123  → clínica full
--   saas@agenciapsi.com.br           senha: Teste@123  → admin da plataforma
--
-- =============================================================================

BEGIN;

-- ============================================================
-- Helper: cria usuário no auth.users + profile
-- (Supabase não expõe auth.users diretamente, mas em SQL Editor
--  com acesso de service_role podemos inserir diretamente)
-- ============================================================

-- Limpa seeds anteriores se existirem
DELETE FROM auth.users
WHERE email IN (
  'paciente@agenciapsi.com.br',
  'terapeuta@agenciapsi.com.br',
  'clinica1@agenciapsi.com.br',
  'clinica2@agenciapsi.com.br',
  'clinica3@agenciapsi.com.br',
  'saas@agenciapsi.com.br'
);

-- ============================================================
-- 1. Cria usuários no auth.users
-- ============================================================

INSERT INTO auth.users (
  instance_id,
  id,
  email,
  encrypted_password,
  email_confirmed_at,
  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
  -- Paciente
  (
    '00000000-0000-0000-0000-000000000000',
    'aaaaaaaa-0001-0001-0001-000000000001',
    'paciente@agenciapsi.com.br',
    crypt('Teste@123', gen_salt('bf')),
    now(), now(), now(), now(),
    '{"name": "Ana Paciente"}'::jsonb,
    '{"provider": "email", "providers": ["email"]}'::jsonb,
    'authenticated', 'authenticated', false, false, '', '', '', '', ''
  ),
  -- Terapeuta
  (
    '00000000-0000-0000-0000-000000000000',
    'aaaaaaaa-0002-0002-0002-000000000002',
    'terapeuta@agenciapsi.com.br',
    crypt('Teste@123', gen_salt('bf')),
    now(), now(), now(), now(),
    '{"name": "Bruno Terapeuta"}'::jsonb,
    '{"provider": "email", "providers": ["email"]}'::jsonb,
    'authenticated', 'authenticated', false, false, '', '', '', '', ''
  ),
  -- Clínica 1 — Coworking
  (
    '00000000-0000-0000-0000-000000000000',
    'aaaaaaaa-0003-0003-0003-000000000003',
    'clinica1@agenciapsi.com.br',
    crypt('Teste@123', gen_salt('bf')),
    now(), now(), now(), now(),
    '{"name": "Clínica Espaço Psi"}'::jsonb,
    '{"provider": "email", "providers": ["email"]}'::jsonb,
    'authenticated', 'authenticated', false, false, '', '', '', '', ''
  ),
  -- Clínica 2 — Recepção
  (
    '00000000-0000-0000-0000-000000000000',
    'aaaaaaaa-0004-0004-0004-000000000004',
    'clinica2@agenciapsi.com.br',
    crypt('Teste@123', gen_salt('bf')),
    now(), now(), now(), now(),
    '{"name": "Clínica Mente Sã"}'::jsonb,
    '{"provider": "email", "providers": ["email"]}'::jsonb,
    'authenticated', 'authenticated', false, false, '', '', '', '', ''
  ),
  -- Clínica 3 — Full
  (
    '00000000-0000-0000-0000-000000000000',
    'aaaaaaaa-0005-0005-0005-000000000005',
    'clinica3@agenciapsi.com.br',
    crypt('Teste@123', gen_salt('bf')),
    now(), now(), now(), now(),
    '{"name": "Clínica Bem Estar"}'::jsonb,
    '{"provider": "email", "providers": ["email"]}'::jsonb,
    'authenticated', 'authenticated', false, false, '', '', '', '', ''
  ),
  -- SaaS Admin
  (
    '00000000-0000-0000-0000-000000000000',
    'aaaaaaaa-0006-0006-0006-000000000006',
    'saas@agenciapsi.com.br',
    crypt('Teste@123', gen_salt('bf')),
    now(), now(), now(), now(),
    '{"name": "Admin Plataforma"}'::jsonb,
    '{"provider": "email", "providers": ["email"]}'::jsonb,
    'authenticated', 'authenticated', false, false, '', '', '', '', ''
  );

-- auth.identities (obrigatório para GoTrue reconhecer login email/senha)
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-0001-0001-0001-000000000001', 'paciente@agenciapsi.com.br',  'email', '{"sub": "aaaaaaaa-0001-0001-0001-000000000001", "email": "paciente@agenciapsi.com.br",  "email_verified": true}'::jsonb, now(), now(), now()),
  (gen_random_uuid(), 'aaaaaaaa-0002-0002-0002-000000000002', 'terapeuta@agenciapsi.com.br', 'email', '{"sub": "aaaaaaaa-0002-0002-0002-000000000002", "email": "terapeuta@agenciapsi.com.br", "email_verified": true}'::jsonb, now(), now(), now()),
  (gen_random_uuid(), 'aaaaaaaa-0003-0003-0003-000000000003', 'clinica1@agenciapsi.com.br',  'email', '{"sub": "aaaaaaaa-0003-0003-0003-000000000003", "email": "clinica1@agenciapsi.com.br",  "email_verified": true}'::jsonb, now(), now(), now()),
  (gen_random_uuid(), 'aaaaaaaa-0004-0004-0004-000000000004', 'clinica2@agenciapsi.com.br',  'email', '{"sub": "aaaaaaaa-0004-0004-0004-000000000004", "email": "clinica2@agenciapsi.com.br",  "email_verified": true}'::jsonb, now(), now(), now()),
  (gen_random_uuid(), 'aaaaaaaa-0005-0005-0005-000000000005', 'clinica3@agenciapsi.com.br',  'email', '{"sub": "aaaaaaaa-0005-0005-0005-000000000005", "email": "clinica3@agenciapsi.com.br",  "email_verified": true}'::jsonb, now(), now(), now()),
  (gen_random_uuid(), 'aaaaaaaa-0006-0006-0006-000000000006', 'saas@agenciapsi.com.br',      'email', '{"sub": "aaaaaaaa-0006-0006-0006-000000000006", "email": "saas@agenciapsi.com.br",      "email_verified": true}'::jsonb, now(), now(), now())
ON CONFLICT (provider, provider_id) DO NOTHING;


-- ============================================================
-- 2. Profiles (o trigger handle_new_user não dispara em inserts
--    diretos no auth.users via SQL, então criamos manualmente)
-- ============================================================

INSERT INTO public.profiles (id, role, account_type, full_name)
VALUES
  ('aaaaaaaa-0001-0001-0001-000000000001', 'portal_user',   'patient',   'Ana Paciente'),
  ('aaaaaaaa-0002-0002-0002-000000000002', 'tenant_member', 'therapist', 'Bruno Terapeuta'),
  ('aaaaaaaa-0003-0003-0003-000000000003', 'tenant_member', 'clinic',    'Clínica Espaço Psi'),
  ('aaaaaaaa-0004-0004-0004-000000000004', 'tenant_member', 'clinic',    'Clínica Mente Sã'),
  ('aaaaaaaa-0005-0005-0005-000000000005', 'tenant_member', 'clinic',    'Clínica Bem Estar'),
  ('aaaaaaaa-0006-0006-0006-000000000006', 'saas_admin',    'free',      'Admin Plataforma')
ON CONFLICT (id) DO UPDATE SET
  role         = EXCLUDED.role,
  account_type = EXCLUDED.account_type,
  full_name    = EXCLUDED.full_name;


-- ============================================================
-- 3. SaaS Admin na tabela saas_admins
-- ============================================================

INSERT INTO public.saas_admins (user_id, created_at)
VALUES ('aaaaaaaa-0006-0006-0006-000000000006', now())
ON CONFLICT (user_id) DO NOTHING;


-- ============================================================
-- 4. Tenant do terapeuta
-- ============================================================

INSERT INTO public.tenants (id, name, kind, created_at)
VALUES ('bbbbbbbb-0002-0002-0002-000000000002', 'Bruno Terapeuta', 'therapist', now())
ON CONFLICT (id) DO NOTHING;

INSERT INTO public.tenant_members (tenant_id, user_id, role, status, created_at)
VALUES ('bbbbbbbb-0002-0002-0002-000000000002', 'aaaaaaaa-0002-0002-0002-000000000002', 'tenant_admin', 'active', now())
ON CONFLICT (tenant_id, user_id) DO NOTHING;

DO $$ BEGIN PERFORM public.seed_determined_commitments('bbbbbbbb-0002-0002-0002-000000000002'); END $$;


-- ============================================================
-- 5. Tenant da Clínica 1 — Coworking
-- ============================================================

INSERT INTO public.tenants (id, name, kind, created_at)
VALUES ('bbbbbbbb-0003-0003-0003-000000000003', 'Clínica Espaço Psi', 'clinic_coworking', now())
ON CONFLICT (id) DO NOTHING;

INSERT INTO public.tenant_members (tenant_id, user_id, role, status, created_at)
VALUES ('bbbbbbbb-0003-0003-0003-000000000003', 'aaaaaaaa-0003-0003-0003-000000000003', 'tenant_admin', 'active', now())
ON CONFLICT (tenant_id, user_id) DO NOTHING;

DO $$ BEGIN PERFORM public.seed_determined_commitments('bbbbbbbb-0003-0003-0003-000000000003'); END $$;


-- ============================================================
-- 6. Tenant da Clínica 2 — Recepção
-- ============================================================

INSERT INTO public.tenants (id, name, kind, created_at)
VALUES ('bbbbbbbb-0004-0004-0004-000000000004', 'Clínica Mente Sã', 'clinic_reception', now())
ON CONFLICT (id) DO NOTHING;

INSERT INTO public.tenant_members (tenant_id, user_id, role, status, created_at)
VALUES ('bbbbbbbb-0004-0004-0004-000000000004', 'aaaaaaaa-0004-0004-0004-000000000004', 'tenant_admin', 'active', now())
ON CONFLICT (tenant_id, user_id) DO NOTHING;

DO $$ BEGIN PERFORM public.seed_determined_commitments('bbbbbbbb-0004-0004-0004-000000000004'); END $$;


-- ============================================================
-- 7. Tenant da Clínica 3 — Full
-- ============================================================

INSERT INTO public.tenants (id, name, kind, created_at)
VALUES ('bbbbbbbb-0005-0005-0005-000000000005', 'Clínica Bem Estar', 'clinic_full', now())
ON CONFLICT (id) DO NOTHING;

INSERT INTO public.tenant_members (tenant_id, user_id, role, status, created_at)
VALUES ('bbbbbbbb-0005-0005-0005-000000000005', 'aaaaaaaa-0005-0005-0005-000000000005', 'tenant_admin', 'active', now())
ON CONFLICT (tenant_id, user_id) DO NOTHING;

DO $$ BEGIN PERFORM public.seed_determined_commitments('bbbbbbbb-0005-0005-0005-000000000005'); END $$;


-- ============================================================
-- 8. Subscriptions ativas para cada conta
-- ============================================================

-- Terapeuta → plano 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-0002-0002-0002-000000000002',
  p.id, p.key, 'active', 'month',
  now(), now() + interval '30 days',
  'seed', now(), now()
FROM public.plans p WHERE p.key = 'therapist_free';

-- Clínica 1 → plano clinic_free
INSERT INTO public.subscriptions (
  tenant_id, plan_id, plan_key, status, interval,
  current_period_start, current_period_end,
  source, started_at, activated_at
)
SELECT
  'bbbbbbbb-0003-0003-0003-000000000003',
  p.id, p.key, 'active', 'month',
  now(), now() + interval '30 days',
  'seed', now(), now()
FROM public.plans p WHERE p.key = 'clinic_free';

-- Clínica 2 → plano clinic_free
INSERT INTO public.subscriptions (
  tenant_id, plan_id, plan_key, status, interval,
  current_period_start, current_period_end,
  source, started_at, activated_at
)
SELECT
  'bbbbbbbb-0004-0004-0004-000000000004',
  p.id, p.key, 'active', 'month',
  now(), now() + interval '30 days',
  'seed', now(), now()
FROM public.plans p WHERE p.key = 'clinic_free';

-- Clínica 3 → plano clinic_free
INSERT INTO public.subscriptions (
  tenant_id, plan_id, plan_key, status, interval,
  current_period_start, current_period_end,
  source, started_at, activated_at
)
SELECT
  'bbbbbbbb-0005-0005-0005-000000000005',
  p.id, p.key, 'active', 'month',
  now(), now() + interval '30 days',
  'seed', now(), now()
FROM public.plans p WHERE p.key = 'clinic_free';

-- Paciente → plano patient_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-0001-0001-0001-000000000001',
  p.id, p.key, 'active', 'month',
  now(), now() + interval '30 days',
  'seed', now(), now()
FROM public.plans p WHERE p.key = 'patient_free';


-- ============================================================
-- 9. Vincula terapeuta à Clínica 3 (full) como exemplo
-- ============================================================

INSERT INTO public.tenant_members (tenant_id, user_id, role, status, created_at)
VALUES (
  'bbbbbbbb-0005-0005-0005-000000000005',
  'aaaaaaaa-0002-0002-0002-000000000002',
  'therapist',
  'active',
  now()
)
ON CONFLICT (tenant_id, user_id) DO NOTHING;


-- ============================================================
-- 10. Confirma
-- ============================================================

DO $$
BEGIN
  RAISE NOTICE '✅ Seed aplicado com sucesso.';
  RAISE NOTICE '';
  RAISE NOTICE '  Usuários criados:';
  RAISE NOTICE '  paciente@agenciapsi.com.br   → patient';
  RAISE NOTICE '  terapeuta@agenciapsi.com.br  → therapist (tenant próprio + vinculado à Clínica 3)';
  RAISE NOTICE '  clinica1@agenciapsi.com.br   → clinic_coworking';
  RAISE NOTICE '  clinica2@agenciapsi.com.br   → clinic_reception';
  RAISE NOTICE '  clinica3@agenciapsi.com.br   → clinic_full';
  RAISE NOTICE '  saas@agenciapsi.com.br       → saas_admin';
  RAISE NOTICE '  Senha de todos: Teste@123';
END;
$$;

COMMIT;
