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

/** Una sanción (baneo o muteo) de la cuenta. Textos visibles como claves i18n. */
export interface Sanction {
  scopeKey: 'account' | 'battlenet' | 'character'
  scopeName: string // nombre del personaje (solo para scopeKey='character')
  reason: string // motivo escrito por el GM (dato, no se traduce)
  by: string // quién sancionó (dato)
  date: Date
  expires: Date | null // null = permanente
  active: boolean
  statusKey: 'active' | 'activePermanent' | 'expired'
}

/** Estado de un baneo a partir de sus timestamps UNIX (segundos) y el flag active. */
function banState(
  bandate: number,
  unbandate: number,
  active?: number,
): { active: boolean; statusKey: Sanction['statusKey']; expires: Date | null } {
  const now = Math.floor(Date.now() / 1000)
  const permanent = unbandate === 0 || unbandate <= bandate
  const flagActive = active === undefined ? true : active === 1
  const stillActive = flagActive && (permanent || unbandate > now)
  return {
    active: stillActive,
    statusKey: stillActive ? (permanent ? 'activePermanent' : 'active') : 'expired',
    expires: permanent ? null : new Date(unbandate * 1000),
  }
}

/**
 * Historial de sanciones de una cuenta desde las BD de AzerothCore:
 *  - Baneos: `acore_auth.account_banned` (cuenta de juego), `battlenet_account_bans`
 *    (cuenta Battle.net) y `acore_characters.character_banned` (personajes de la cuenta).
 *  - Muteos: `acore_auth.account_muted` (por cuenta de juego).
 * Cada consulta es tolerante a fallos (devuelve [] si la tabla no existe / AC no
 * está poblado) para no romper la página. Ordenado por fecha descendente.
 */
export async function getSanctions(accountId: number, bnetId?: number): Promise<{ bans: Sanction[]; mutes: Sanction[] }> {
  const bans: Sanction[] = []
  const mutes: Sanction[] = []
  if (!accountId) return { bans, mutes }

  // 1) Baneos de la cuenta de juego.
  try {
    const [rows] = await db(DB.auth).query<RowDataPacket[]>(
      'SELECT bandate, unbandate, bannedby, banreason, active FROM account_banned WHERE id = ? ORDER BY bandate DESC',
      [accountId],
    )
    for (const r of rows) {
      const s = banState(Number(r.bandate), Number(r.unbandate), Number(r.active))
      bans.push({ scopeKey: 'account', scopeName: '', reason: String(r.banreason || '—'), by: String(r.bannedby || '—'), date: new Date(Number(r.bandate) * 1000), ...s })
    }
  } catch {
    /* AC no poblado */
  }

  // 2) Baneos de la cuenta Battle.net (sin columna active).
  if (bnetId) {
    try {
      const [rows] = await db(DB.auth).query<RowDataPacket[]>(
        'SELECT bandate, unbandate, bannedby, banreason FROM battlenet_account_bans WHERE id = ? ORDER BY bandate DESC',
        [bnetId],
      )
      for (const r of rows) {
        const s = banState(Number(r.bandate), Number(r.unbandate))
        bans.push({ scopeKey: 'battlenet', scopeName: '', reason: String(r.banreason || '—'), by: String(r.bannedby || '—'), date: new Date(Number(r.bandate) * 1000), ...s })
      }
    } catch {
      /* AC no poblado */
    }
  }

  // 3) Baneos de personaje (de los personajes de la cuenta).
  try {
    const [chars] = await db(DB.characters).query<RowDataPacket[]>('SELECT guid, name FROM characters WHERE account = ?', [accountId])
    if (chars.length > 0) {
      const nameByGuid = new Map<number, string>(chars.map((c) => [Number(c.guid), String(c.name)]))
      const guids = [...nameByGuid.keys()]
      const [rows] = await db(DB.characters).query<RowDataPacket[]>(
        `SELECT guid, bandate, unbandate, bannedby, banreason, active FROM character_banned WHERE guid IN (${guids.map(() => '?').join(',')}) ORDER BY bandate DESC`,
        guids,
      )
      for (const r of rows) {
        const s = banState(Number(r.bandate), Number(r.unbandate), Number(r.active))
        bans.push({ scopeKey: 'character', scopeName: nameByGuid.get(Number(r.guid)) ?? '?', reason: String(r.banreason || '—'), by: String(r.bannedby || '—'), date: new Date(Number(r.bandate) * 1000), ...s })
      }
    }
  } catch {
    /* AC no poblado */
  }

  // 4) Muteos de la cuenta de juego (mutetime = fin del muteo).
  try {
    const [rows] = await db(DB.auth).query<RowDataPacket[]>(
      'SELECT mutedate, mutetime, mutedby, mutereason FROM account_muted WHERE guid = ? ORDER BY mutedate DESC',
      [accountId],
    )
    const now = Math.floor(Date.now() / 1000)
    for (const r of rows) {
      const end = Number(r.mutetime)
      const active = end > now
      mutes.push({
        scopeKey: 'account',
        scopeName: '',
        reason: String(r.mutereason || '—'),
        by: String(r.mutedby || '—'),
        date: new Date(Number(r.mutedate) * 1000),
        expires: end > 0 ? new Date(end * 1000) : null,
        active,
        statusKey: active ? 'active' : 'expired',
      })
    }
  } catch {
    /* AC no poblado */
  }

  bans.sort((a, b) => b.date.getTime() - a.date.getTime())
  mutes.sort((a, b) => b.date.getTime() - a.date.getTime())
  return { bans, mutes }
}
