// ─── Material Crafting Actions ─────────────────────────────────────────────────
// Separate file to avoid exceeding the 400-line limit in craftingStore.ts.

import { useManaStore } from '../stores/manaStore';
import { useUIStore } from '../stores/uiStore';
import {
  getFabricatorRecipe,
  deductFabricatorMana,
  deductMaterials,
} from '../crafting-fabricator';

export interface CraftMaterialResult {
  success: boolean;
  newMaterials?: Record<string, number>;
}

export function craftMaterial(
  recipeId: string,
  lootInventoryMaterials: Record<string, number>,
): CraftMaterialResult {
  const recipe = getFabricatorRecipe(recipeId);
  if (!recipe || recipe.recipeType !== 'material') return { success: false };
  if (!recipe.resultMaterial || !recipe.resultAmount) return { success: false };

  const rawMana = useManaStore.getState().rawMana;
  const elements = useManaStore.getState().elements;

  const deducted = deductFabricatorMana(recipe, rawMana, elements);
  if (!deducted) return { success: false };

  const newMaterials = deductMaterials(recipe, lootInventoryMaterials);
  newMaterials[recipe.resultMaterial] = (newMaterials[recipe.resultMaterial] || 0) + recipe.resultAmount;

  useManaStore.setState({ rawMana: deducted.rawMana, elements: deducted.elements });
  useUIStore.getState().addLog(`✨ Crafted ${recipe.resultAmount}x ${recipe.name}!`);

  return { success: true, newMaterials };
}
