// ─── Enchantment Application Actions ────────────────────────────────────────

import type { CraftingState } from '../stores/craftingStore.types';
import type { GameAction } from '../types';
import * as CraftingApply from '../crafting-apply';

/**
 * Start applying an enchantment design to an equipment instance.
 * Note: currentAction must be passed from the combat store.
 */
export function startApplying(
  equipmentInstanceId: string,
  designId: string,
  get: () => CraftingState,
  set: (partial: Partial<CraftingState>) => void,
  currentAction: GameAction,
): boolean {
  const state = get();
  const instance = state.equipmentInstances[equipmentInstanceId];
  const design = state.enchantmentDesigns.find(d => d.id === designId);

  const validation = CraftingApply.canApplyEnchantment(
    instance,
    design,
    currentAction
  );
  if (!validation.canApply) return false;

  set({
    applicationProgress: CraftingApply.initializeApplicationProgress(
      equipmentInstanceId,
      designId,
      design!
    ),
  });

  return true;
}

export function pauseApplication(
  get: () => CraftingState,
  set: (partial: Partial<CraftingState>) => void
) {
  const state = get();
  if (!state.applicationProgress) return;
  set({
    applicationProgress: {
      ...state.applicationProgress,
      paused: true,
    },
  });
}

export function resumeApplication(
  get: () => CraftingState,
  set: (partial: Partial<CraftingState>) => void
) {
  const state = get();
  if (!state.applicationProgress) return;
  set({
    applicationProgress: {
      ...state.applicationProgress,
      paused: false,
    },
  });
}

export function cancelApplication(
  set: (partial: Partial<CraftingState>) => void
) {
  set({
    applicationProgress: null,
  });
}
