import { executeSoapCommand } from './soap'
import { creditDPoints } from './dpoints'
import { checkFactionChangeEligibility } from './change-faction'
import {
  getRenamePrice,
  getCustomizePrice,
  getChangeRacePrice,
  getChangeFactionPrice,
  getLevelUpPrice,
  getTransferPrice,
  goldPriceFor,
} from './prices'

type Meta = Record<string, string>

export interface PaidServiceConfig {
  price: (meta: Meta) => Promise<number>
  productName: (character: string, meta: Meta) => string
  fulfill: (character: string, meta: Meta) => Promise<boolean>
  extraFields: string[] // campos (además de character) que el form envía y se guardan en metadata
  // Comprobación previa al pago (p.ej. condiciones de cambio de facción). Si `ok`
  // es false, se bloquea el checkout y se muestra `message`.
  precheck?: (accountId: number, character: string) => Promise<{ ok: boolean; message?: string }>
}

async function soapFulfill(command: string): Promise<boolean> {
  return (await executeSoapCommand(command)) !== null
}

/** Nombre de personaje válido (evita inyección en el comando SOAP). */
const SAFE_NAME = /^[A-Za-z]{1,12}$/

/** Envía el oro por correo al personaje (como el diseño). Requiere el worldserver. */
async function sendGoldByMail(character: string, goldAmount: number): Promise<boolean> {
  if (!SAFE_NAME.test(character) || !(goldAmount > 0)) return false
  const copper = goldAmount * 10000
  return soapFulfill(`.send money "${character}" "Adquirir oro" "Has recibido ${goldAmount} de oro." ${copper}`)
}

export const PAID_SERVICES: Record<string, PaidServiceConfig> = {
  rename: {
    price: () => getRenamePrice(),
    productName: (c) => `Renombrar personaje: ${c}`,
    fulfill: (c) => soapFulfill(`.char rename ${c}`),
    extraFields: [],
  },
  customize: {
    price: () => getCustomizePrice(),
    productName: (c) => `Personalizar personaje: ${c}`,
    fulfill: (c) => soapFulfill(`.char customi ${c}`),
    extraFields: [],
  },
  'change-race': {
    price: () => getChangeRacePrice(),
    productName: (c) => `Cambiar raza: ${c}`,
    fulfill: (c) => soapFulfill(`.char changerace ${c}`),
    extraFields: [],
  },
  'change-faction': {
    price: () => getChangeFactionPrice(),
    productName: (c) => `Cambiar facción: ${c}`,
    fulfill: (c) => soapFulfill(`.char changef ${c}`),
    precheck: async (accountId, character) => {
      const r = await checkFactionChangeEligibility(accountId, character)
      return { ok: r.ok, message: r.ok ? undefined : `No se puede cambiar la facción: el personaje ${r.reasons.join('; ')}.` }
    },
    extraFields: [],
  },
  'level-up': {
    price: () => getLevelUpPrice(),
    productName: (c) => `Subir a nivel 80: ${c}`,
    fulfill: (c) => soapFulfill(`.char level ${c} 80`),
    extraFields: [],
  },
  gold: {
    price: (m) => goldPriceFor(Number(m.gold_amount)),
    productName: (c, m) => `Adquirir oro: ${m.gold_amount} al personaje ${c}`,
    fulfill: (c, m) => sendGoldByMail(c, Number(m.gold_amount)),
    extraFields: ['gold_amount'],
  },
  transfer: {
    price: () => getTransferPrice(),
    productName: (c, m) => `Transferir ${c} a la cuenta ${m.destination_account}`,
    fulfill: (c, m) => soapFulfill(`.char changeaccount ${m.destination_account} ${c}`),
    extraFields: ['destination_account'],
  },
  // Compra de PD (Adquirir PD): acredita puntos a la cuenta que hizo el pago.
  // El importe lo elige el usuario, por eso `price` lee metadata.amount.
  dpoints: {
    price: (m) => Promise.resolve(Number(m.amount)),
    productName: (_c, m) => `${Number(m.points)} PD`,
    fulfill: (_c, m) => creditDPoints(Number(m.accountId), Number(m.points)),
    extraFields: [],
  },
}

export function getPaidService(slug: string): PaidServiceConfig | null {
  return PAID_SERVICES[slug] ?? null
}
