// ─── Disenchanting Actions ─────────────────────────────────────────────────

import type { CraftingState } from '../stores/craftingStore.types';
import { useManaStore } from '../stores/manaStore';

export function disenchantEquipment(
  instanceId: string,
  get: () => CraftingState,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void
) {
  const state = get();
  const instance = state.equipmentInstances[instanceId];
  if (!instance || instance.enchantments.length === 0) return;

  const disenchantLevel = 0;
  const recoveryRate = 0.1 + disenchantLevel * 0.2;

  let totalRecovered = 0;
  for (const ench of instance.enchantments) {
    totalRecovered += Math.floor(ench.actualCost * recoveryRate);
  }

  // Credit recovered mana to raw mana pool
  if (totalRecovered > 0) {
    useManaStore.setState((s) => ({ rawMana: s.rawMana + totalRecovered }));
  }

  set((s) => ({
    equipmentInstances: {
      ...s.equipmentInstances,
      [instanceId]: {
        ...instance,
        enchantments: [],
        usedCapacity: 0,
        rarity: 'common',
        tags: [...(instance.tags || []), 'Ready for Enchantment'],
      },
    },
    log: [`✨ Disenchanted ${instance.name}, recovered ${totalRecovered} mana.`],
  }));
}
