-- Nova40 Demo User Seeder
-- Run this in Supabase SQL Editor
--
-- Creates: demo@nova40.app / 123456 (pre-confirmed, ready to login)

-- Step 1: Create the demo user in auth.users
do $$
declare
  demo_uid uuid := gen_random_uuid();
begin
  -- Skip if demo user already exists
  if exists (select 1 from auth.users where email = 'demo@nova40.app') then
    raise notice 'Demo user already exists, skipping.';
    return;
  end if;

  -- Insert into auth.users with minimal required columns
  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
  ) values (
    demo_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 into auth.identities (required for sign-in to work)
  insert into auth.identities (
    id,
    user_id,
    provider_id,
    identity_data,
    provider,
    last_sign_in_at,
    created_at,
    updated_at
  ) values (
    demo_uid,
    demo_uid,
    'demo@nova40.app',
    jsonb_build_object(
      'sub', demo_uid::text,
      'email', 'demo@nova40.app',
      'email_verified', true
    ),
    'email',
    now(),
    now(),
    now()
  );

  raise notice 'Demo user created successfully (id: %)', demo_uid;
end $$;

-- Verify: you should see one row
select id, email, email_confirmed_at from auth.users where email = 'demo@nova40.app';
