import type { RowDataPacket } from 'mysql2'
import { db, DB } from './db'
import { buildConcept, purchasedPD } from './tx-concept'

/**
 * Un movimiento del historial de PD/PV. Los textos visibles se devuelven como
 * CLAVES para que la página los traduzca (i18n): `method`, `status` y el concepto
 * (`conceptKey` + `conceptArgs`, con `conceptRaw` de reserva para textos libres
 * heredados que no tienen clave).
 */
export interface PointsMovement {
  date: Date
  conceptKey: string | null // p.ej. 'pd','vote','promo','rename','gold'…
  conceptArgs: Record<string, string | number>
  conceptRaw: string // reserva (product_name) cuando conceptKey es null
  method: 'Stripe' | 'SumUp' | 'vote' | 'promo'
  pd: number | null
  pv: number | null
  amount: number | null // € (pagos), null si no aplica
  status: 'delivered' | 'pending' | 'credited'
}

/** Saldos actuales de PD y PV de una cuenta de juego. */
export async function getPointsBalances(accountId: number): Promise<{ dp: number; pv: number }> {
  if (!accountId) return { dp: 0, pv: 0 }
  try {
    const [rows] = await db(DB.default).query<RowDataPacket[]>(
      'SELECT dp, vp FROM api_points WHERE accountID = ?',
      [accountId],
    )
    return rows[0] ? { dp: Number(rows[0].dp), pv: Number(rows[0].vp) } : { dp: 0, pv: 0 }
  } catch {
    return { dp: 0, pv: 0 }
  }
}

/**
 * Historial unificado de PD/PV de una cuenta, combinando las fuentes reales:
 *  - `stripelog`: pagos por **Stripe** (mode test/live) y **SumUp** (mode sumup).
 *  - `votelog` (+ `votesite`): PV ganados al votar.
 *  - `promoredemption` (+ `promocode`): PD/PV canjeados por código.
 * Ordenado por fecha descendente; cada consulta es tolerante a fallos.
 */
export async function getPointsHistory(accountId: number, limit = 100): Promise<PointsMovement[]> {
  if (!accountId) return []
  const movements: PointsMovement[] = []

  // 1) Pagos (Stripe + SumUp).
  try {
    const [rows] = await db(DB.default).query<RowDataPacket[]>(
      'SELECT product_name, character_name, amount, mode, service, metadata, fulfilled, timestamp ' +
        'FROM stripelog WHERE account_id = ? ORDER BY timestamp DESC LIMIT ?',
      [accountId, limit],
    )
    for (const r of rows) {
      const service = r.service ? String(r.service) : null
      const productName = String(r.product_name || '—')
      const metadata = r.metadata ? String(r.metadata) : null
      const c = buildConcept(productName, service, String(r.character_name || ''), metadata)
      movements.push({
        date: new Date(r.timestamp),
        conceptKey: c.conceptKey,
        conceptArgs: c.conceptArgs,
        conceptRaw: c.conceptRaw,
        method: r.mode === 'sumup' ? 'SumUp' : 'Stripe',
        pd: purchasedPD(productName, service, metadata),
        pv: null,
        amount: Number(r.amount),
        status: r.fulfilled ? 'delivered' : 'pending',
      })
    }
  } catch {
    /* tabla ausente: se omite */
  }

  // 2) Votos (PV).
  try {
    const [rows] = await db(DB.default).query<RowDataPacket[]>(
      'SELECT v.created_at, s.name, s.points FROM votelog v ' +
        'JOIN votesite s ON s.id = v.vote_site_id WHERE v.account_id = ? ORDER BY v.created_at DESC LIMIT ?',
      [accountId, limit],
    )
    for (const r of rows) {
      movements.push({
        date: new Date(r.created_at),
        conceptKey: 'vote',
        conceptArgs: { detail: String(r.name || '') },
        conceptRaw: `Voto en ${r.name}`,
        method: 'vote',
        pd: null,
        pv: Number(r.points) || 0,
        amount: null,
        status: 'credited',
      })
    }
  } catch {
    /* tabla ausente: se omite */
  }

  // 3) Promociones (PD/PV).
  try {
    const [rows] = await db(DB.default).query<RowDataPacket[]>(
      'SELECT r.redeemed_at, c.code, c.pd, c.pv FROM promoredemption r ' +
        'JOIN promocode c ON c.id = r.promo_id WHERE r.account_id = ? ORDER BY r.redeemed_at DESC LIMIT ?',
      [accountId, limit],
    )
    for (const r of rows) {
      movements.push({
        date: new Date(r.redeemed_at),
        conceptKey: 'promo',
        conceptArgs: { detail: String(r.code || '') },
        conceptRaw: `Código ${r.code}`,
        method: 'promo',
        pd: Number(r.pd) > 0 ? Number(r.pd) : null,
        pv: Number(r.pv) > 0 ? Number(r.pv) : null,
        amount: null,
        status: 'credited',
      })
    }
  } catch {
    /* tabla ausente: se omite */
  }

  movements.sort((a, b) => b.date.getTime() - a.date.getTime())
  return movements.slice(0, limit)
}
