import crypto from 'node:crypto'
import type { RowDataPacket } from 'mysql2'
import { db, DB } from './db'
import { sendMail } from './mail'
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 home_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 home_securitytoken WHERE user_id = ?', [userId])
  await db(DB.default).query(
    'INSERT INTO home_securitytoken (token, created_at, expires_at, ip_address, user_id) VALUES (?, NOW(), ?, ?, ?)',
    [token, expiresAt, ip || '0.0.0.0', userId],
  )

  await sendMail(
    email,
    'Token de seguridad - Nova WoW',
    `<!DOCTYPE html><html lang="es"><body style="font-family:Arial,sans-serif;background:#1b120b;color:#e8dccb;padding:24px">
      <div style="max-width:600px;margin:0 auto;background:#241812;border:1px solid #4a3320;border-radius:8px;padding:28px">
        <h1 style="color:#d79602">Nova WoW</h1><h2>Token de seguridad</h2>
        <p>Tu token de seguridad es:</p>
        <p style="font-size:28px;letter-spacing:4px;color:#d79602;font-weight:bold">${token}</p>
        <p style="font-size:13px;color:#b1997f">Consérvalo en un lugar seguro. Se solicitará para acciones importantes de la cuenta.</p>
      </div></body></html>`,
  )

  const [created] = await db(DB.default).query<RowDataPacket[]>(
    'SELECT created_at FROM home_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 home_securitytoken WHERE user_id = ? ORDER BY created_at DESC LIMIT 1',
    [userId],
  )
  return Boolean(rows[0] && rows[0].token === token)
}
