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

async function priceFrom(table: string, fallback: number): Promise<number> {
  try {
    const [rows] = await db(DB.default).query<RowDataPacket[]>(`SELECT price FROM ${table} LIMIT 1`)
    return rows[0] ? Number(rows[0].price) : fallback
  } catch {
    return fallback
  }
}

export const getRenamePrice = () => priceFrom('renameprice', 2.0)
export const getCustomizePrice = () => priceFrom('customizeprice', 1.0)
export const getChangeRacePrice = () => priceFrom('changeraceprice', 10.0)
export const getChangeFactionPrice = () => priceFrom('changefactionprice', 10.0)
export const getLevelUpPrice = () => priceFrom('levelupprice', 10.0)
export const getTransferPrice = () => priceFrom('transferprice', 10.0)
// OJO: la tabla `restoreitemprice` NO existe en la BD, así que esto siempre cae
// al valor por defecto (el catch de priceFrom se come el error). Viene de antes;
// si se quiere un precio configurable, hay que crear la tabla.
export const getRestoreItemPrice = () => priceFrom('restoreitemprice', 1.0)

export interface GoldOption {
  gold_amount: number
  price: number
}

export async function getGoldOptions(): Promise<GoldOption[]> {
  try {
    const [rows] = await db(DB.default).query<RowDataPacket[]>(
      'SELECT gold_amount, price FROM goldprice ORDER BY gold_amount',
    )
    return rows.map((r) => ({ gold_amount: r.gold_amount, price: Number(r.price) }))
  } catch {
    return []
  }
}

/** Precio de una cantidad de oro concreta (0 si no existe esa opción). */
export async function goldPriceFor(goldAmount: number): Promise<number> {
  const opts = await getGoldOptions()
  return opts.find((o) => o.gold_amount === goldAmount)?.price ?? 0
}
