const Player = require("../models/Player");
const { Op } = require("sequelize");

class EconomyService {
  constructor() {
    this.onlinePlayers = new Set();
  }

  init(io) {
    setInterval(async () => {
      if (this.onlinePlayers.size === 0) return;

      const ids = Array.from(this.onlinePlayers);
      try {
        await Player.increment("credits", {
          by: 1,
          where: { id: { [Op.in]: ids } },
        });

        await Player.update(
          { lastCreditUpdate: new Date() },
          { where: { id: { [Op.in]: ids } } },
        );

        const updatedPlayers = await Player.findAll({
          where: { id: { [Op.in]: ids } },
          attributes: ["id", "credits"],
        });

        updatedPlayers.forEach((p) => {
          const targetSocket = Array.from(io.sockets.sockets.values()).find(
            (s) => s.playerId === p.id,
          );

          if (targetSocket) {
            targetSocket.emit("player:credits_update", {
              totalCredits: p.credits,
            });
          }
        });
      } catch (err) {
        console.error("Economy online error:", err);
      }
    }, 10000);
  }

  addPlayer(id) {
    this.onlinePlayers.add(id);
  }
  removePlayer(id) {
    this.onlinePlayers.delete(id);
  }

  async handleOfflineEarnings(player) {
    const now = new Date();
    const lastUpdate = new Date(player.lastCreditUpdate || player.updatedAt);
    const secondsPassed = Math.floor((now - lastUpdate) / 1000);

    const offlineCredits = Math.floor(secondsPassed / 20);

    if (offlineCredits > 0) {
      await player.increment("credits", { by: offlineCredits });
      await player.reload();
      await player.update({ lastCreditUpdate: now });
      return offlineCredits;
    }
    return 0;
  }
}

module.exports = new EconomyService();
