/**
 * Admin roles + system admin user seed — admin-dashboard.
 *
 * Seeds:
 *  1. Three built-in admin_roles (SUPER_ADMIN, SUPPORT, BILLING) with their
 *     permission arrays.
 *  2. A bootstrap SUPER_ADMIN admin_user account (email from env or default)
 *     with role_id pointing to SUPER_ADMIN.
 *
 * Returns the SUPER_ADMIN admin_users.id for use by downstream seeds (e.g.
 * tax-rates, which need a valid created_by FK).
 *
 * Idempotent: uses onConflictDoNothing. If the roles and user already exist,
 * returns the existing SUPER_ADMIN user id.
 */
import { eq } from 'drizzle-orm'
import { DEFAULT_ADMIN_ROLES } from '@zync/types'
import type { Db } from '../client'
import { adminRoles } from '../schema/admin-rbac'
import { adminUsers } from '../schema/admin'

const BOOTSTRAP_ADMIN_EMAIL = process.env.BOOTSTRAP_ADMIN_EMAIL ?? 'admin@zync.is'
const BOOTSTRAP_ADMIN_PASSWORD_HASH =
  process.env.BOOTSTRAP_ADMIN_PASSWORD_HASH ??
  // bcrypt hash of 'changeme' — must be replaced in production
  '$2b$12$placeholder.hash.change.in.production.admin.zync'

/**
 * Seed admin roles + bootstrap admin user.
 * Returns the SUPER_ADMIN admin_user id for downstream FK usage.
 */
export async function seedAdminRoles(db: Db): Promise<string> {
  // 1. Insert the three system roles
  await db
    .insert(adminRoles)
    .values(
      DEFAULT_ADMIN_ROLES.map((r) => ({
        name: r.name,
        isSystemRole: r.isSystemRole,
        permissions: [...r.permissions],
      })),
    )
    .onConflictDoNothing()

  // 2. Resolve SUPER_ADMIN role id
  const [superAdminRole] = await db
    .select({ id: adminRoles.id })
    .from(adminRoles)
    .where(eq(adminRoles.name, 'SUPER_ADMIN'))
    .limit(1)

  if (!superAdminRole) {
    throw new Error('SUPER_ADMIN role not found after seed — this should not happen')
  }

  // 3. Insert bootstrap admin user with SUPER_ADMIN role
  await db
    .insert(adminUsers)
    .values({
      email: BOOTSTRAP_ADMIN_EMAIL,
      passwordHash: BOOTSTRAP_ADMIN_PASSWORD_HASH,
      status: 'active',
    })
    .onConflictDoNothing()

  // 4. Resolve the admin user id
  const [adminUser] = await db
    .select({ id: adminUsers.id })
    .from(adminUsers)
    .where(eq(adminUsers.email, BOOTSTRAP_ADMIN_EMAIL))
    .limit(1)

  if (!adminUser) {
    throw new Error('Bootstrap admin user not found after seed — this should not happen')
  }

  console.log(`Seeded 3 admin roles + bootstrap admin user (${BOOTSTRAP_ADMIN_EMAIL}).`)
  return adminUser.id
}
