import crypto from 'node:crypto'
import type { RowDataPacket } from 'mysql2'
import { db, DB } from './db'
import { sendMail } from './mail'
import { securityTokenEmailHtml } from './emails'
import type { SessionData } from './session'

export interface Result {
  success: boolean
  error?: string
  tokenDate?: string
}

/** Solicita un token de seguridad (6 caracteres) por email. 1 cada 7 días. */
export async function requestSecurityToken(session: SessionData, ip: string): Promise<Result> {
  const userId = session.accountId ?? 0
  const email = session.bnetEmail ?? ''
  if (!email) return { success: false, error: 'noEmail' }

  const [existing] = await db(DB.default).query<RowDataPacket[]>(
    'SELECT id, created_at FROM securitytoken WHERE user_id = ? ORDER BY created_at DESC LIMIT 1',
    [userId],
  )
  if (existing[0]) {
    const days = (Date.now() - new Date(existing[0].created_at).getTime()) / 86400_000
    if (days < 7) return { success: false, error: 'cooldown' }
  }

  const token = crypto.randomBytes(4).toString('base64url').slice(0, 6)
  const expiresAt = new Date(Date.now() + 7 * 86400_000)

  await db(DB.default).query('DELETE FROM securitytoken WHERE user_id = ?', [userId])
  await db(DB.default).query(
    'INSERT INTO securitytoken (token, created_at, expires_at, ip_address, user_id) VALUES (?, NOW(), ?, ?, ?)',
    [token, expiresAt, ip || '0.0.0.0', userId],
  )

  // La cuenta es el correo: con Battle.net se entra con él, no con un usuario.
  await sendMail(email, 'Token de seguridad - NightSpire', securityTokenEmailHtml(email, token, ip || '0.0.0.0'))

  const [created] = await db(DB.default).query<RowDataPacket[]>(
    'SELECT created_at FROM securitytoken WHERE user_id = ? ORDER BY created_at DESC LIMIT 1',
    [userId],
  )
  return { success: true, tokenDate: created[0] ? new Date(created[0].created_at).toISOString() : undefined }
}

/** Comprueba que el token coincide con el de la cuenta. */
export async function checkSecurityToken(userId: number, token: string): Promise<boolean> {
  const [rows] = await db(DB.default).query<RowDataPacket[]>(
    'SELECT token FROM securitytoken WHERE user_id = ? ORDER BY created_at DESC LIMIT 1',
    [userId],
  )
  return Boolean(rows[0] && rows[0].token === token)
}
