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

// Servicios con precio único (una fila) -> tabla django_wow.
export const PRICE_TABLES: Record<string, string> = {
  rename: 'renameprice',
  customize: 'customizeprice',
  'change-race': 'changeraceprice',
  'change-faction': 'changefactionprice',
  'level-up': 'levelupprice',
  transfer: 'transferprice',
}

export interface PriceRow {
  service: string
  price: number
}

export async function getAllPrices(): Promise<PriceRow[]> {
  const out: PriceRow[] = []
  for (const [service, table] of Object.entries(PRICE_TABLES)) {
    let price = 0
    try {
      const [rows] = await db(DB.default).query<RowDataPacket[]>(`SELECT price FROM ${table} LIMIT 1`)
      price = rows[0] ? Number(rows[0].price) : 0
    } catch {
      /* ignore */
    }
    out.push({ service, price })
  }
  return out
}

/** Fija el precio (fila única) de un servicio. */
export async function setPrice(service: string, value: number): Promise<boolean> {
  const table = PRICE_TABLES[service]
  if (!table || !(value >= 0)) return false
  await db(DB.default).query(`DELETE FROM ${table}`)
  await db(DB.default).query(`INSERT INTO ${table} (price) VALUES (?)`, [value])
  return true
}
