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('home_renameprice', 2.0)
export const getCustomizePrice = () => priceFrom('home_customizeprice', 1.0)
export const getChangeRacePrice = () => priceFrom('home_changeraceprice', 10.0)
export const getChangeFactionPrice = () => priceFrom('home_changefactionprice', 10.0)
export const getLevelUpPrice = () => priceFrom('home_levelupprice', 10.0)
export const getTransferPrice = () => priceFrom('home_transferprice', 10.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 home_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
}
