-- WA Conversion Tracker: setup untuk trial. Jalankan setelah 03_functions.sql.

-- BAGIAN A: migrasi (kolom tambahan hasil analisis AI)
alter table lead_scores
  add column if not exists amount_hint numeric(14, 2),
  add column if not exists product_hint text,
  add column if not exists stages jsonb not null default '[]';

-- BAGIAN B: akun pertama
-- 1) Buat user dulu di Supabase Dashboard > Authentication > Users > Add user
--    (isi email + password, centang Auto Confirm User).
-- 2) Ganti v_email di bawah dengan email itu, lalu jalankan blok ini.
-- Hasilnya: akun tersebut jadi Super Admin sekaligus Owner dari satu perusahaan trial.
do $$
declare
  v_email text := 'GANTI_DENGAN_EMAIL_KAMU';
  v_name  text := 'Admin';
  v_user  uuid;
  v_org   uuid;
begin
  select id into v_user from auth.users where email = v_email;
  if v_user is null then
    raise exception 'User % belum dibuat di Authentication > Users', v_email;
  end if;

  insert into profiles (id, full_name, is_super_admin) values (v_user, v_name, true)
  on conflict (id) do update
    set is_super_admin = true, full_name = coalesce(profiles.full_name, excluded.full_name);

  insert into organizations (name, slug) values ('Perusahaan Trial', 'trial')
  on conflict (slug) do update set name = excluded.name
  returning id into v_org;

  insert into memberships (org_id, user_id, role) values (v_org, v_user, 'owner')
  on conflict (org_id, user_id) do nothing;

  insert into meta_connections (org_id, dataset_id) values (v_org, '')
  on conflict (org_id) do nothing;
end $$;
