// ─── Enchantment Design Actions ────────────────────────────────────────────

import type { CraftingState } from '../stores/craftingStore.types';
import type { EnchantmentDesign, DesignEffect } from '../types';
import * as CraftingUtils from '../crafting-utils';
import * as CraftingDesign from '../crafting-design';
import { computeEffects } from '../effects/upgrade-effects';
import { hasSpecial, SPECIAL_EFFECTS } from '../effects/special-effects';

export interface DesignActionsParams {
  skills: Record<string, number>;
  skillUpgrades: Record<string, string[]>;
  skillTiers: Record<string, number>;
}

export function startDesigningEnchantment(
  name: string,
  equipmentTypeId: string,
  effects: DesignEffect[],
  params: DesignActionsParams,
  get: () => CraftingState,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void
): boolean {
  const state = get();
  const enchantingLevel = params.skills.enchanting || 0;
  const validation = CraftingDesign.validateDesignEffects(
    effects,
    equipmentTypeId,
    enchantingLevel
  );
  if (!validation.valid) return false;

  const equipType = CraftingUtils.getEquipmentType(equipmentTypeId);
  if (!equipType) return false;

  const efficiencyBonus = ((params.skillUpgrades || {})['efficientEnchant'] || [])?.length * 0.05 || 0;
  const totalCapacityCost = CraftingDesign.calculateDesignCapacityCost(effects, efficiencyBonus);

  if (totalCapacityCost > equipType.baseCapacity) {
    return false;
  }

  const computedEffects = computeEffects(params.skillUpgrades || {}, params.skillTiers || {});
  const hasEnchantMastery = hasSpecial(computedEffects, SPECIAL_EFFECTS.ENCHANT_MASTERY);

  let updates: Partial<CraftingState> = {};

  if (!state.designProgress) {
    updates = {
      designProgress: {
        designId: CraftingUtils.generateDesignId(),
        progress: 0,
        required: CraftingDesign.calculateDesignTime(effects),
        name,
        equipmentType: equipmentTypeId,
        effects,
      },
    };
  } else if (hasEnchantMastery && !state.designProgress2) {
    updates = {
      designProgress2: {
        designId: CraftingUtils.generateDesignId(),
        progress: 0,
        required: CraftingDesign.calculateDesignTime(effects),
        name,
        equipmentType: equipmentTypeId,
        effects,
      },
    };
  } else {
    return false;
  }

  set(() => updates);
  return true;
}

export function cancelDesign(
  get: () => CraftingState,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void
) {
  const state = get();
  if (state.designProgress2 && !state.designProgress) {
    set(() => ({ designProgress2: null }));
  } else {
    set(() => ({
      designProgress: null,
    }));
  }
}

export function saveDesign(
  design: EnchantmentDesign,
  get: () => CraftingState,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void
) {
  const state = get();
  if (state.designProgress2 && state.designProgress2.designId === design.id) {
    set((s) => ({
      enchantmentDesigns: [...s.enchantmentDesigns, design],
      designProgress2: null,
    }));
  } else {
    set((s) => ({
      enchantmentDesigns: [...s.enchantmentDesigns, design],
      designProgress: null,
    }));
  }
}

export function deleteDesign(
  designId: string,
  set: (fn: (state: CraftingState) => Partial<CraftingState>) => void
) {
  set((state) => ({
    enchantmentDesigns: state.enchantmentDesigns.filter(d => d.id !== designId),
  }));
}
