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

export interface BnetAccount {
  id: number
  email: string
}

export interface GameAccount {
  id: number
  username: string
  index: number
}

/** Verifica email+password contra battlenet_accounts (SRP6 v2). Null si falla. */
export async function authenticate(email: string, password: string): Promise<BnetAccount | null> {
  try {
    const [rows] = await db(DB.auth).query<RowDataPacket[]>(
      'SELECT id, email, salt, verifier FROM battlenet_accounts WHERE email = ?',
      [normalizeEmail(email)],
    )
    const row = rows[0]
    if (!row) return null
    const salt: Buffer | null = row.salt ?? null
    const verifier: Buffer | null = row.verifier ?? null
    if (!bnetVerify(email, password, salt, verifier)) return null
    return { id: row.id, email: row.email }
  } catch {
    // La BD de cuentas (AzerothCore) puede no estar disponible/poblada.
    return null
  }
}

/** Cuentas de juego enlazadas a una cuenta Battle.net. */
export async function getGameAccounts(bnetId: number): Promise<GameAccount[]> {
  try {
    const [rows] = await db(DB.auth).query<RowDataPacket[]>(
      'SELECT id, username, battlenet_index FROM account WHERE battlenet_account = ? ORDER BY battlenet_index',
      [bnetId],
    )
    return rows.map((r) => ({ id: r.id, username: r.username, index: r.battlenet_index }))
  } catch {
    return []
  }
}
