import { spendDPoints, creditDPoints, PD_PER_UNIT } from './dpoints' /** Coste en PD de un precio en euros (100 PD = 1 €). */ export function dpointsCost(priceEur: number): number { return Math.round(priceEur * PD_PER_UNIT) } /** * Paga un servicio con el saldo PD: descuenta el coste de forma atómica y * ejecuta la acción al momento (sin pasarela). Si la ejecución falla, reembolsa * el saldo. Devuelve `insufficientPd` si no hay saldo suficiente. */ export async function payServiceWithDPoints( accountId: number, priceEur: number, fulfill: () => Promise, ): Promise<{ success: boolean; error?: string }> { const cost = dpointsCost(priceEur) if (!(cost > 0)) return { success: false, error: 'invalidRequest' } const spent = await spendDPoints(accountId, cost) if (!spent.success) { return { success: false, error: spent.error === 'insufficientFunds' ? 'insufficientPd' : 'genericError' } } let ok = false try { ok = await fulfill() } catch { ok = false } if (!ok) { await creditDPoints(accountId, cost) // reembolso si no se pudo ejecutar return { success: false, error: 'fulfillFailed' } } return { success: true } }