// ─── Enchantment Preparation Actions ────────────────────────────────────────

import type { CraftingState } from '../stores/craftingStore.types';
import * as CraftingPrep from '../crafting-prep';
import { useManaStore } from '../stores/manaStore';
import { useUIStore } from '../stores/uiStore';

export function startPreparing(
  equipmentInstanceId: string,
  rawMana: number,
  get: () => CraftingState,
  set: (partial: Partial<CraftingState>) => void
): boolean {
  const state = get();
  const instance = state.equipmentInstances[equipmentInstanceId];

  const validation = CraftingPrep.canPrepareEquipment(
    instance,
    instance?.tags || []
  );
  if (!validation.canPrepare) return false;

  if (!instance) return false;

  const costs = CraftingPrep.calculatePreparationCosts(instance.totalCapacity);

  if (rawMana < costs.manaTotal) return false;

  // Deduct the preparation mana cost from the player's raw mana pool
  useManaStore.setState((s) => ({ rawMana: s.rawMana - costs.manaTotal }));

  set({
    preparationProgress: CraftingPrep.initializePreparationProgress(
      equipmentInstanceId,
      instance.totalCapacity
    ),
  });

  return true;
}

export function cancelPreparation(
  get: () => CraftingState,
  set: (partial: Partial<CraftingState>) => void
) {
  const state = get();
  const progress = state.preparationProgress;
  if (!progress) return;

  // Refund mana proportionally to remaining progress
  const remainingFraction = progress.required > 0
    ? Math.max(0, (progress.required - progress.progress) / progress.required)
    : 1;
  // Full refund for unspent progress, 50% for spent progress
  const refundRate = remainingFraction + (1 - remainingFraction) * 0.5;
  const manaRefund = Math.floor(progress.manaCostPaid * refundRate);

  if (manaRefund > 0) {
    useManaStore.setState((s) => ({ rawMana: s.rawMana + manaRefund }));
  }
  useUIStore.getState().addLog(`🚫 Preparation cancelled. Refunded ${manaRefund} mana.`);
  set({
    preparationProgress: null,
  });
}
