-- Nova40: Fix auth schema and create demo user
-- Run this in Supabase SQL Editor
--
-- This script:
-- 1. Cleans up any broken demo user entries from previous seeder attempts
-- 2. Verifies auth schema health
-- 3. Creates a proper demo user

-- ============================================
-- STEP 1: Clean up any broken demo user data
-- ============================================
delete from auth.identities
where user_id in (select id from auth.users where email = 'demo@nova40.app');

delete from auth.users
where email = 'demo@nova40.app';

-- ============================================
-- STEP 2: Verify auth schema is healthy
-- ============================================
-- This should return a number (0 is fine)
select count(*) as total_users from auth.users;

-- ============================================
-- STEP 3: Create demo user properly
-- ============================================
-- We need the pgcrypto extension for crypt()
create extension if not exists pgcrypto;

do $$
declare
  new_uid uuid := gen_random_uuid();
begin
  -- Insert user
  insert into auth.users (
    id,
    instance_id,
    aud,
    role,
    email,
    encrypted_password,
    email_confirmed_at,
    raw_app_meta_data,
    raw_user_meta_data,
    created_at,
    updated_at,
    confirmation_token,
    recovery_token,
    email_change_token_new,
    email_change
  ) values (
    new_uid,
    '00000000-0000-0000-0000-000000000000',
    'authenticated',
    'authenticated',
    'demo@nova40.app',
    crypt('123456', gen_salt('bf')),
    now(),
    '{"provider": "email", "providers": ["email"]}'::jsonb,
    '{"email": "demo@nova40.app"}'::jsonb,
    now(),
    now(),
    '',
    '',
    '',
    ''
  );

  -- Insert identity (REQUIRED for Supabase auth login to work)
  insert into auth.identities (
    id,
    user_id,
    provider_id,
    identity_data,
    provider,
    last_sign_in_at,
    created_at,
    updated_at
  ) values (
    new_uid,
    new_uid,
    'demo@nova40.app',
    jsonb_build_object(
      'sub', new_uid::text,
      'email', 'demo@nova40.app',
      'email_verified', true
    ),
    'email',
    now(),
    now(),
    now()
  );

  raise notice '✅ Demo user created! ID: %', new_uid;
end $$;

-- ============================================
-- STEP 4: Verify the user was created
-- ============================================
select
  u.id,
  u.email,
  u.email_confirmed_at,
  i.provider
from auth.users u
left join auth.identities i on i.user_id = u.id
where u.email = 'demo@nova40.app';
