// ─── Equipment Crafting Actions ────────────────────────────────────────────
// Note: The main implementation is now in craftingStore.ts
// These wrappers are kept for backward compatibility but are no longer used directly

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

export function startCraftingEquipment(
  blueprintId: string,
  get: () => CraftingState,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void,
  rawMana: number,
  currentAction: GameAction,
): boolean {
  const state = get();

  const check = CraftingEquipment.canStartEquipmentCrafting(
    blueprintId,
    state.lootInventory.blueprints.includes(blueprintId),
    state.lootInventory.materials,
    rawMana,
    currentAction
  );

  if (!check.canCraft) return false;

  const result = CraftingEquipment.initializeEquipmentCrafting(
    blueprintId,
    state.lootInventory.materials,
    rawMana
  );

  set((s) => ({
    lootInventory: {
      ...s.lootInventory,
      materials: result.newMaterials,
    },
    equipmentCraftingProgress: result.progress,
  }));

  return true;
}

export function cancelEquipmentCrafting(
  _get: () => CraftingState,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void
) {
  set((state) => {
    const progress = state.equipmentCraftingProgress;
    if (!progress) return { equipmentCraftingProgress: null };

    const cancelResult = CraftingEquipment.cancelEquipmentCrafting(
      progress.blueprintId,
      progress.manaSpent
    );

    return {
      equipmentCraftingProgress: null,
      log: [cancelResult.logMessage],
    };
  });
}

export function deleteMaterial(
  materialId: string,
  amount: number,
  _get: () => CraftingState,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void
) {
  set((state) => {
    const newMaterials = { ...state.lootInventory.materials };
    const currentAmount = newMaterials[materialId] || 0;
    const newAmount = Math.max(0, currentAmount - amount);

    if (newAmount <= 0) {
      delete newMaterials[materialId];
    } else {
      newMaterials[materialId] = newAmount;
    }

    return {
      lootInventory: {
        ...state.lootInventory,
        materials: newMaterials,
      },
      log: [`🗑️ Deleted ${amount}x ${materialId}.`],
    };
  });
}
