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

import type { GameState } from '../types';
import * as CraftingApply from '../crafting-apply';

export function startApplying(
  equipmentInstanceId: string,
  designId: string,
  get: () => GameState,
  set: (fn: (state: GameState) => Partial<GameState>) => void
): boolean {
  const state = get();
  const instance = state.equipmentInstances[equipmentInstanceId];
  const design = state.enchantmentDesigns.find(d => d.id === designId);

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

  set(() => ({
    currentAction: 'enchant' as const,
    applicationProgress: CraftingApply.initializeApplicationProgress(
      equipmentInstanceId,
      designId,
      design!
    ),
  }));

  return true;
}

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

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

export function cancelApplication(
  set: (fn: (state: GameState) => Partial<GameState>) => void
) {
  set(() => ({
    currentAction: 'meditate' as const,
    applicationProgress: null,
  }));
}
