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

export interface BattlepayOrder {
  id: number
  reference: string
  product_id: number
  product_name: string
  price_eur: number
  status: string
  created_at: number | null
}

/** Órdenes Battlepay PENDING de una cuenta de juego. */
export async function getPendingOrders(accountId: number): Promise<BattlepayOrder[]> {
  try {
    const [rows] = await db(DB.auth).query<RowDataPacket[]>(
      "SELECT id, reference, product_id, product_name, price_eur, status, created_at " +
        "FROM battlepay_orders WHERE account_id = ? AND status = 'PENDING' ORDER BY created_at DESC",
      [accountId],
    )
    return rows.map((r) => ({
      id: r.id,
      reference: r.reference,
      product_id: r.product_id,
      product_name: r.product_name,
      price_eur: Number(r.price_eur),
      status: r.status,
      created_at: r.created_at ?? null,
    }))
  } catch {
    return []
  }
}

/** Orden PENDING concreta que pertenece a la cuenta (para crear el pago). */
export async function getPendingOrder(
  reference: string,
  accountId: number,
): Promise<{ product_name: string; price_eur: number } | null> {
  const [rows] = await db(DB.auth).query<RowDataPacket[]>(
    "SELECT product_name, price_eur FROM battlepay_orders WHERE reference = ? AND account_id = ? AND status = 'PENDING'",
    [reference, accountId],
  )
  return rows[0] ? { product_name: rows[0].product_name, price_eur: Number(rows[0].price_eur) } : null
}

/** Marca una orden como PAID solo si estaba PENDING. Devuelve true si cambió algo. */
export async function markOrderPaid(reference: string): Promise<boolean> {
  const [res] = await db(DB.auth).query<ResultSetHeader>(
    "UPDATE battlepay_orders SET status = 'PAID', paid_at = UNIX_TIMESTAMP() WHERE reference = ? AND status = 'PENDING'",
    [reference],
  )
  return res.affectedRows > 0
}
