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

class ChatManager {
  async getGlobalHistory(limit = 50) {
    try {
      return await Message.findAll({
        where: { type: "global" },
        limit,
        order: [["createdAt", "ASC"]],
        include: [
          {
            model: Player,
            as: "sender",
            attributes: ["username"],
          },
        ],
      });
    } catch (error) {
      console.error("History Error:", error);
      return [];
    }
  }

  async saveMessage({ content, type, senderId, receiverId = null }) {
    try {
      const newMessage = await Message.create({
        content,
        type,
        senderId,
        receiverId,
      });
      const sender = await Player.findByPk(senderId, {
        attributes: ["username"],
      });

      return {
        id: newMessage.id,
        content: newMessage.content,
        type: newMessage.type,
        senderId: newMessage.senderId,
        senderName: sender ? sender.username : "Unknown",
        receiverId: newMessage.receiverId,
        createdAt: newMessage.createdAt,
      };
    } catch (error) {
      console.error("Save Message Error:", error);
      throw error;
    }
  }
  async getPrivateHistory(myId, friendId, limit = 50) {
    try {
      return await Message.findAll({
        where: {
          type: "private",
          [Op.or]: [
            { senderId: myId, receiverId: friendId },
            { senderId: friendId, receiverId: myId },
          ],
        },
        limit,
        order: [["createdAt", "ASC"]],
        include: [
          {
            model: Player,
            as: "sender",
            attributes: ["username"],
          },
        ],
      });
    } catch (error) {
      console.error("Private History Error:", error);
      return [];
    }
  }
  async searchPlayers(query, excludeId) {
    try {
      return await Player.findAll({
        where: {
          username: { [Op.like]: `%${query}%` },
          id: { [Op.ne]: excludeId },
        },
        attributes: ["id", "username", "level"],
        limit: 10,
      });
    } catch (error) {
      console.error("Search Error:", error);
      return [];
    }
  }
}

module.exports = new ChatManager();
