-- ============================================================
-- Script: crear primer usuario platform_admin
--
-- USO:
--   docker exec -i supabase-db psql -U postgres -d postgres \
--     -v email='admin@ejemplo.com' -v password='CAMBIAR' \
--     < scripts/setup_first_admin.sql
--
-- NOTA: las variables psql solo funcionan en SQL plano, no en DO $$.
-- Este script usa un CTE INSERT...RETURNING para encadenar ambos inserts.
--
-- CAMBIAR CONTRASEÑA LUEGO DEL PRIMER LOGIN:
--   docker exec -i supabase-db psql -U postgres -d postgres \
--     -c "UPDATE auth.users SET encrypted_password = extensions.crypt('NuevaContraseña', extensions.gen_salt('bf')) WHERE email = 'admin@ejemplo.com';"
-- ============================================================

WITH new_user AS (
  INSERT INTO auth.users (
    id,
    instance_id,
    aud,
    role,
    email,
    encrypted_password,
    email_confirmed_at,
    created_at,
    updated_at,
    raw_app_meta_data,
    raw_user_meta_data,
    confirmation_token,
    recovery_token,
    is_super_admin
  ) VALUES (
    gen_random_uuid(),
    '00000000-0000-0000-0000-000000000000',
    'authenticated',
    'authenticated',
    :'email',
    extensions.crypt(:'password', extensions.gen_salt('bf')),
    now(),
    now(),
    now(),
    '{"provider":"email","providers":["email"]}',
    '{}',
    '',
    '',
    false
  )
  RETURNING id, email
)
INSERT INTO public.user_roles (user_id, app_role, org_id)
SELECT id, 'platform_admin', '10000000-0000-0000-0000-000000000002'
FROM new_user
RETURNING (SELECT email FROM new_user), user_id;
