const datapackLoader = require("../game/DatapackLoader");
const { Inventory } = require("../models");

class CraftManager {
  constructor() {
    this.activeCrafts = new Map();
  }

  async startCraft(userId, recipeId, socket) {
    if (this.activeCrafts.has(userId)) return { error: "Already crafting" };

    const recipe = datapackLoader.getRecipe(recipeId);
    if (!recipe) return { error: "Recipe not found" };

    const craftTimeMs = (recipe.time_seconds || 0) * 1000;
    const finishAt = Date.now() + craftTimeMs;

    const craftData = {
      recipeId,
      finishAt,
      totalTime: recipe.time_seconds,
      timer: setTimeout(
        () => this.completeCraft(userId, recipeId, socket),
        craftTimeMs,
      ),
    };

    this.activeCrafts.set(userId, craftData);
    return { recipeId, finishAt, totalTime: recipe.time_seconds };
  }

  async completeCraft(userId, recipeId, socket) {
    try {
      const recipe = datapackLoader.getRecipe(recipeId);
      const outputItemId = Object.keys(recipe.output)[0];
      const outputQuantity = recipe.output[outputItemId];

      const [newItem, created] = await Inventory.findOrCreate({
        where: { playerId: userId, itemId: outputItemId },
        defaults: { quantity: outputQuantity },
      });

      if (!created) {
        await newItem.increment("quantity", { by: outputQuantity });
      }

      this.activeCrafts.delete(userId);

      if (socket && socket.connected) {
        socket.emit("player:craft_success", { recipeId });
        socket.emit("player:get_inventory");
      }
    } catch (err) {
      console.error("Complete craft error:", err);
    }
  }

  getExistingCraft(userId) {
    const craft = this.activeCrafts.get(userId);
    if (craft && craft.finishAt > Date.now()) {
      return {
        recipeId: craft.recipeId,
        finishAt: craft.finishAt,
        totalTime: craft.totalTime,
      };
    }
    return null;
  }
}

module.exports = new CraftManager();
