import { executeSql, queryJson, sqlLiteral } from '../src/lite/pg.mjs'

const bootstrapPhone = String(process.env.BOOTSTRAP_SUPER_ADMIN_PHONE || '15842430688').replace(/\D/g, '')
const bootstrapName = String(process.env.BOOTSTRAP_SUPER_ADMIN_NAME || '超级管理员').trim() || '超级管理员'
const bootstrapEmail = `${bootstrapPhone}@staff.dlbdi.local`
const demoPhones = [
  '13900000001',
  '13900000002',
  '13900000003',
  '13900000004',
  '13900000005',
  '13900000006',
  '13900000007',
  '13900000008',
]

if (!/^1\d{10}$/.test(bootstrapPhone)) {
  throw new Error(`BOOTSTRAP_SUPER_ADMIN_PHONE is invalid: ${bootstrapPhone}`)
}

await executeSql(`
  alter table staff_accounts
    alter column password_salt drop not null,
    alter column password_hash drop not null,
    alter column password_salt set default '',
    alter column password_hash set default '';

  update staff_accounts
  set password_salt = '',
      password_hash = '',
      updated_at = now()
  where coalesce(password_salt, '') <> ''
     or coalesce(password_hash, '') <> '';
`)

const summary = await queryJson(`
  with role_upsert as (
    insert into staff_roles (code, name, description, default_entry, status, permissions)
    values (
      'super_admin',
      '超级管理员',
      '平台初始化生成的最高权限岗位，负责员工、角色、财务、内容和全部业务配置。',
      '/admin',
      'active',
      array['*']::text[]
    )
    on conflict (code) do update set
      name = excluded.name,
      description = excluded.description,
      default_entry = excluded.default_entry,
      status = 'active',
      permissions = excluded.permissions,
      updated_at = now()
    returning code
  ),
  disabled_demo as (
    update staff_accounts
    set status = 'disabled',
        remark = '历史种子账号已停用；内部账号仅使用手机号验证码登录。',
        updated_at = now()
    where phone = any(array[${demoPhones.map(sqlLiteral).join(', ')}]::text[])
      and phone <> ${sqlLiteral(bootstrapPhone)}
      and status <> 'disabled'
    returning id
  ),
  bootstrap_account as (
    insert into staff_accounts (
      email, phone, display_name, role, status, position_title, remark, password_salt, password_hash
    )
    values (
      ${sqlLiteral(bootstrapEmail)},
      ${sqlLiteral(bootstrapPhone)},
      ${sqlLiteral(bootstrapName)},
      'super_admin',
      'active',
      '超级管理员',
      '初始化超级管理员；仅使用手机号验证码登录。',
      '',
      ''
    )
    on conflict (phone) where phone <> '' do update set
      display_name = excluded.display_name,
      role = 'super_admin',
      status = 'active',
      position_title = excluded.position_title,
      remark = case
        when staff_accounts.remark = '' then excluded.remark
        when staff_accounts.remark like '%初始化超级管理员%' then staff_accounts.remark
        else trim(both from concat_ws(' ', staff_accounts.remark, excluded.remark))
      end,
      password_salt = '',
      password_hash = '',
      updated_at = now()
    returning id, phone, display_name, role, status
  )
  select json_build_object(
    'bootstrap', (select row_to_json(bootstrap_account) from bootstrap_account),
    'disabledDemoCount', (select count(*)::int from disabled_demo)
  );
`)

console.log(JSON.stringify(summary, null, 2))
