import type { Character } from '@/lib/schemas/character';
import type { EnforceResult } from './result';

/**
 * Spend `n` of a tracked resource pool (ki, rage, channel divinity, sorcery
 * points, …). Pure; fails without mutation when the pool is too low.
 */
export function spendResource(c: Character, resourceId: string, n = 1): EnforceResult {
  const r = c.resources.find((x) => x.id === resourceId);
  if (!r) return { ok: false, reason: 'That resource does not exist.' };
  if (n <= 0) return { ok: false, reason: 'Amount must be positive.' };
  if (r.current < n) return { ok: false, reason: `Not enough ${r.name} (have ${r.current}, need ${n}).` };
  return {
    ok: true,
    patch: { resources: c.resources.map((x) => (x.id === resourceId ? { ...x, current: x.current - n } : x)) },
    log: [`Spent ${n} ${r.name}.`],
  };
}

/** Restore `n` to a resource pool, capped at its max. */
export function regainResource(c: Character, resourceId: string, n = 1): EnforceResult {
  const r = c.resources.find((x) => x.id === resourceId);
  if (!r) return { ok: false, reason: 'That resource does not exist.' };
  return {
    ok: true,
    patch: { resources: c.resources.map((x) => (x.id === resourceId ? { ...x, current: Math.min(x.max, x.current + n) } : x)) },
    log: [`Regained ${n} ${r.name}.`],
  };
}
