import type { RowDataPacket } from 'mysql2'
import { db, DB } from './db'
import { normalizeEmail } from './bnet'
import type { SessionData } from './session'

/** ¿Es administrador? Por allowlist de email (ADMIN_EMAILS) o por gmlevel de AzerothCore. */
export async function isAdmin(session: SessionData): Promise<boolean> {
  if (!session.bnetId) return false

  const allow = (process.env.ADMIN_EMAILS || '')
    .split(',')
    .map((e) => normalizeEmail(e))
    .filter(Boolean)
  if (session.bnetEmail && allow.includes(normalizeEmail(session.bnetEmail))) return true

  try {
    const level = Number(process.env.ADMIN_GMLEVEL || 3)
    const [rows] = await db(DB.auth).query<RowDataPacket[]>(
      'SELECT SecurityLevel AS gmlevel FROM account_access WHERE AccountID = ? ORDER BY SecurityLevel DESC LIMIT 1',
      [session.accountId ?? 0],
    )
    if (rows[0] && Number(rows[0].gmlevel) >= level) return true
  } catch {
    // account_access puede no existir (acore sin poblar)
  }
  return false
}
