import type { RowDataPacket, ResultSetHeader } from 'mysql2'
import { db, DB } from './db'
import { getClassCss } from './character-info'

/**
 * Recuperar personaje (/restore-character): restaura un personaje borrado.
 * En AzerothCore un personaje borrado queda en `characters` con account=0,
 * deleteInfos_Account/deleteInfos_Name = dueño/nombre originales y deleteDate
 * (unix, segundos). Condiciones: nivel > 60, borrado hace < 30 días, y para
 * Caballeros de la Muerte, la cuenta no puede tener ya un DK activo. 12 h/personaje.
 */

const MAX_AGE_S = 30 * 24 * 60 * 60
const COOLDOWN_MS = 12 * 60 * 60 * 1000

export interface DeletedCharacter {
  guid: number
  name: string
  level: number
  classCss: string
}

/** Personajes borrados de la cuenta que cumplen las condiciones (nivel>60, <30 días). */
export async function getRestorableCharacters(accountId: number): Promise<DeletedCharacter[]> {
  if (!accountId) return []
  try {
    const nowS = Math.floor(Date.now() / 1000)
    const [rows] = await db(DB.characters).query<RowDataPacket[]>(
      'SELECT guid, deleteInfos_Name AS name, level, class FROM characters ' +
        'WHERE deleteInfos_Account = ? AND deleteDate IS NOT NULL AND deleteDate <> 0 ' +
        'AND level > 60 AND deleteDate > ? ORDER BY deleteDate DESC',
      [accountId, nowS - MAX_AGE_S],
    )
    return rows.map((r) => ({ guid: Number(r.guid), name: r.name, level: r.level, classCss: getClassCss(r.class) }))
  } catch {
    return []
  }
}

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

export async function restoreCharacter(accountId: number, guid: number): Promise<Result> {
  if (!accountId || !Number.isInteger(guid) || guid <= 0) return { success: false, error: 'invalidRequest' }

  let name = ''
  let cls = 0
  try {
    const [rows] = await db(DB.characters).query<RowDataPacket[]>(
      'SELECT deleteInfos_Name AS name, deleteInfos_Account, deleteDate, level, class FROM characters WHERE guid = ? LIMIT 1',
      [guid],
    )
    const c = rows[0]
    if (!c || Number(c.deleteInfos_Account) !== accountId) return { success: false, error: 'notFound' }
    if (!c.deleteDate || Number(c.deleteDate) === 0) return { success: false, error: 'notDeleted' }
    if (Number(c.level) <= 60) return { success: false, error: 'levelTooLow' }
    if (Number(c.deleteDate) < Math.floor(Date.now() / 1000) - MAX_AGE_S) return { success: false, error: 'tooOld' }
    name = String(c.name)
    cls = Number(c.class)
  } catch {
    return { success: false, error: 'genericError' }
  }

  // Caballero de la Muerte: no restaurar si ya hay un DK activo en la cuenta.
  if (cls === 6) {
    const [dk] = await db(DB.characters).query<RowDataPacket[]>(
      'SELECT 1 FROM characters WHERE account = ? AND class = 6 AND (deleteDate IS NULL OR deleteDate = 0) LIMIT 1',
      [accountId],
    )
    if (dk[0]) return { success: false, error: 'dkExists' }
  }

  // El nombre original debe estar libre (otro personaje activo podría tenerlo).
  const [taken] = await db(DB.characters).query<RowDataPacket[]>(
    'SELECT 1 FROM characters WHERE name = ? AND (deleteDate IS NULL OR deleteDate = 0) LIMIT 1',
    [name],
  )
  if (taken[0]) return { success: false, error: 'nameTaken' }

  // Cooldown de 12 h por personaje.
  try {
    const [last] = await db(DB.default).query<RowDataPacket[]>(
      'SELECT used_at FROM restorehistory WHERE character_guid = ? ORDER BY used_at DESC LIMIT 1',
      [guid],
    )
    if (last[0] && Date.now() - new Date(last[0].used_at).getTime() < COOLDOWN_MS) {
      return { success: false, error: 'cooldown' }
    }
  } catch {
    /* ignore */
  }

  // Restaura (igual que `.character deleted restore` del core).
  try {
    const [res] = await db(DB.characters).query<ResultSetHeader>(
      "UPDATE characters SET account = ?, name = ?, deleteInfos_Account = 0, deleteInfos_Name = '', deleteDate = NULL " +
        'WHERE guid = ? AND deleteInfos_Account = ? AND deleteDate IS NOT NULL AND deleteDate <> 0',
      [accountId, name, guid, accountId],
    )
    if (res.affectedRows !== 1) return { success: false, error: 'genericError' }
  } catch {
    return { success: false, error: 'genericError' }
  }

  await db(DB.default)
    .query('INSERT INTO restorehistory (character_guid, used_at) VALUES (?, NOW())', [guid])
    .catch(() => {})
  return { success: true, name }
}
