import 'dotenv/config'
import bcrypt from 'bcryptjs'
import { getDb } from '../index.js'
import { operatingModelService } from '../../services/operating-model.js'

async function main() {
  const db = getDb()
  const portalEmail = process.env.PORTAL_BOOTSTRAP_EMAIL || 'portal@sankofa.nexus'
  const portalPassword = process.env.PORTAL_BOOTSTRAP_PASSWORD || 'admin123'

  await db.query(
    `INSERT INTO users (email, name, password_hash, role)
     VALUES ($1, $2, $3, $4)
     ON CONFLICT (email) DO UPDATE SET password_hash = EXCLUDED.password_hash, role = EXCLUDED.role`,
    [portalEmail, 'Portal Operator', await bcrypt.hash(portalPassword, 10), 'ADMIN']
  )

  let tenantId: string
  const existing = await db.query(`SELECT id FROM tenants WHERE domain = $1 LIMIT 1`, [
    'portal.sankofa.nexus',
  ])
  if (existing.rows.length) {
    tenantId = existing.rows[0].id
  } else {
    const billingAccountId = `portal-${Date.now()}`
    const created = await db.query(
      `INSERT INTO tenants (name, domain, billing_account_id, status, tier)
       VALUES ($1, $2, $3, $4, $5)
       RETURNING id`,
      ['Sankofa Sovereign Console', 'portal.sankofa.nexus', billingAccountId, 'ACTIVE', 'SOVEREIGN']
    )
    tenantId = created.rows[0].id
  }

  const users = await db.query(`SELECT id FROM users WHERE email = ANY($1)`, [
    [portalEmail, 'admin@sankofa.nexus'],
  ])
  for (const row of users.rows) {
    await db.query(
      `INSERT INTO tenant_users (tenant_id, user_id, role)
       VALUES ($1, $2, $3)
       ON CONFLICT (tenant_id, user_id) DO UPDATE SET role = EXCLUDED.role`,
      [tenantId, row.id, 'TENANT_OWNER']
    )
  }

  await operatingModelService.bootstrapClientForTenant(tenantId)
  console.log(JSON.stringify({ tenantId, portalEmail }))
  await db.end()
}

main().catch((err) => {
  console.error(err)
  process.exit(1)
})
