// ─── Equipment Management Actions ────────────────────────────────────────────

import type { CraftingState } from '../stores/craftingStore.types';
import type { EquipmentInstance, EquipmentSlot } from '../types';
import * as CraftingUtils from '../crafting-utils';

// Create equipment instance
export function createEquipmentInstance(
  typeId: string,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void
): string | null {
  const type = CraftingUtils.getEquipmentType(typeId);
  if (!type) return null;

  const instanceId = CraftingUtils.generateInstanceId();
  const instance: EquipmentInstance = {
    instanceId,
    typeId,
    name: type.name,
    enchantments: [],
    usedCapacity: 0,
    totalCapacity: type.baseCapacity,
    rarity: 'common',
    quality: 100,
    tags: [],
  };

  set((state) => ({
    equipmentInstances: {
      ...state.equipmentInstances,
      [instanceId]: instance,
    },
  }));

  return instanceId;
}

// Equip item
export function equipItem(
  instanceId: string,
  slot: EquipmentSlot,
  get: () => CraftingState,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void
): boolean {
  const state = get();
  const instance = state.equipmentInstances[instanceId];
  if (!instance) return false;

  if (!CraftingUtils.canEquipInSlot(instance, slot, state.equippedInstances, state.equipmentInstances)) {
    return false;
  }

  let newEquipped = { ...state.equippedInstances };
  for (const [s, id] of Object.entries(newEquipped)) {
    if (id === instanceId) {
      newEquipped[s as EquipmentSlot] = null;
    }
  }

  newEquipped[slot] = instanceId;

  if (CraftingUtils.isTwoHanded(instance.typeId) && slot === 'mainHand') {
    newEquipped.offHand = null;
  }

  set(() => ({ equippedInstances: newEquipped }));
  return true;
}

// Unequip item
export function unequipItem(
  slot: EquipmentSlot,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void
) {
  set((state) => ({
    equippedInstances: {
      ...state.equippedInstances,
      [slot]: null,
    },
  }));
}

// Delete equipment instance
export function deleteEquipmentInstance(
  instanceId: string,
  get: () => CraftingState,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void
) {
  const state = get();
  let newEquipped = { ...state.equippedInstances };
  for (const [slot, id] of Object.entries(newEquipped)) {
    if (id === instanceId) {
      newEquipped[slot as EquipmentSlot] = null;
    }
  }

  const newInstances = { ...state.equipmentInstances };
  delete newInstances[instanceId];

  set(() => ({
    equippedInstances: newEquipped,
    equipmentInstances: newInstances,
  }));
}
