-- =============================================================================
-- SEED 002 — Supervisor e Editor
-- =============================================================================
-- Execute APÓS seed_001.sql
-- Requer: pgcrypto (já ativo no Supabase)
--
-- Cria os seguintes usuários de teste:
--
--   supervisor@agenciapsi.com.br     senha: Teste@123  → supervisor da Clínica 3
--   editor@agenciapsi.com.br         senha: Teste@123  → editor de conteúdo (plataforma)
--
-- UUIDs reservados:
--   Supervisor  → aaaaaaaa-0007-0007-0007-000000000007
--   Editor      → aaaaaaaa-0008-0008-0008-000000000008
--
-- =============================================================================

BEGIN;

-- ============================================================
-- 0. Migration: adiciona platform_roles em profiles (se não existir)
-- ============================================================

ALTER TABLE public.profiles
  ADD COLUMN IF NOT EXISTS platform_roles text[] NOT NULL DEFAULT '{}';

COMMENT ON COLUMN public.profiles.platform_roles IS
  'Papéis globais de plataforma, independentes de tenant. Ex: editor de microlearning. Atribuído pelo saas_admin.';


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

DELETE FROM auth.users
WHERE email IN (
  'supervisor@agenciapsi.com.br',
  'editor@agenciapsi.com.br'
);


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

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
  -- Supervisor
  (
    '00000000-0000-0000-0000-000000000000',
    'aaaaaaaa-0007-0007-0007-000000000007',
    'supervisor@agenciapsi.com.br',
    crypt('Teste@123', gen_salt('bf')),
    now(), now(), now(),
    '{"name": "Carlos Supervisor"}'::jsonb,
    '{"provider": "email", "providers": ["email"]}'::jsonb,
    'authenticated', 'authenticated', false, false, '', '', '', '', ''
  ),
  -- Editor de Conteúdo
  (
    '00000000-0000-0000-0000-000000000000',
    'aaaaaaaa-0008-0008-0008-000000000008',
    'editor@agenciapsi.com.br',
    crypt('Teste@123', gen_salt('bf')),
    now(), now(), now(),
    '{"name": "Diana Editora"}'::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-0007-0007-0007-000000000007',
    'supervisor@agenciapsi.com.br',
    'email',
    '{"sub": "aaaaaaaa-0007-0007-0007-000000000007", "email": "supervisor@agenciapsi.com.br", "email_verified": true}'::jsonb,
    now(), now(), now()
  ),
  (
    gen_random_uuid(),
    'aaaaaaaa-0008-0008-0008-000000000008',
    'editor@agenciapsi.com.br',
    'email',
    '{"sub": "aaaaaaaa-0008-0008-0008-000000000008", "email": "editor@agenciapsi.com.br", "email_verified": true}'::jsonb,
    now(), now(), now()
  )
ON CONFLICT (provider, provider_id) DO NOTHING;


-- ============================================================
-- 4. Profiles
--    Supervisor → tenant_member (papel no tenant via tenant_members.role)
--    Editor     → tenant_member + platform_roles = '{editor}'
-- ============================================================

INSERT INTO public.profiles (id, role, account_type, full_name, platform_roles)
VALUES
  (
    'aaaaaaaa-0007-0007-0007-000000000007',
    'tenant_member',
    'therapist',
    'Carlos Supervisor',
    '{}'
  ),
  (
    'aaaaaaaa-0008-0008-0008-000000000008',
    'tenant_member',
    'therapist',
    'Diana Editora',
    '{editor}'   -- permissão de plataforma: acesso à área do editor
  )
ON CONFLICT (id) DO UPDATE SET
  role            = EXCLUDED.role,
  account_type    = EXCLUDED.account_type,
  full_name       = EXCLUDED.full_name,
  platform_roles  = EXCLUDED.platform_roles;


-- ============================================================
-- 5. Vincula Supervisor à Clínica 3 (Full) com role 'supervisor'
-- ============================================================

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-0007-0007-0007-000000000007',   -- Carlos Supervisor
  'supervisor',
  'active',
  now()
)
ON CONFLICT (tenant_id, user_id) DO UPDATE SET
  role   = EXCLUDED.role,
  status = EXCLUDED.status;


-- ============================================================
-- 6. Vincula Editor à Clínica 3 como terapeuta
--    (contexto de tenant para o editor poder usar /therapist também,
--     se necessário. O papel de editor vem de platform_roles.)
-- ============================================================

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-0008-0008-0008-000000000008',   -- Diana Editora
  'therapist',
  'active',
  now()
)
ON CONFLICT (tenant_id, user_id) DO UPDATE SET
  role   = EXCLUDED.role,
  status = EXCLUDED.status;


-- ============================================================
-- 7. Confirma
-- ============================================================

DO $$
BEGIN
  RAISE NOTICE '✅ Seed 002 aplicado com sucesso.';
  RAISE NOTICE '';
  RAISE NOTICE '  Migration aplicada:';
  RAISE NOTICE '  → profiles.platform_roles text[] adicionada (se não existia)';
  RAISE NOTICE '';
  RAISE NOTICE '  Usuários criados:';
  RAISE NOTICE '  supervisor@agenciapsi.com.br  → supervisor da Clínica Bem Estar (Full)';
  RAISE NOTICE '  editor@agenciapsi.com.br      → editor de conteúdo (platform_roles = {editor})';
  RAISE NOTICE '  Senha de todos: Teste@123';
END;
$$;

COMMIT;
