const { Player, Friend } = require("../models");
const notificationManager = require("./NotificationManager");
const { Op } = require("sequelize");

class SocialManager {
  constructor() {
    this.io = null;
  }

  init(io) {
    this.io = io;
  }

  async searchPlayers(query, excludeId) {
    return await Player.findAll({
      where: {
        username: { [Op.like]: `%${query}%` },
        id: { [Op.ne]: excludeId },
      },
      limit: 5,
      attributes: ["id", "username", "level"],
    });
  }
  async removeFriend(myId, friendId) {
    await Friend.destroy({
      where: {
        [Op.or]: [
          { playerId: myId, friendId: friendId },
          { playerId: friendId, friendId: myId },
        ],
      },
    });

    await this.broadcastFriendListUpdate(myId);
    await this.broadcastFriendListUpdate(friendId);
  }
  async sendFriendRequest(sender, targetId) {
    await notificationManager.send({
      playerId: targetId,
      type: "friend_request",
      title: "NEW FRIEND REQUEST",
      message: `${sender.username} wants to add you as a friend.`,
      data: { fromId: sender.id },
      priority: "normal",
    });
  }

  async acceptFriendRequest(myId, friendId, notificationId) {
    const exists = await Friend.findOne({
      where: { playerId: myId, friendId: friendId },
    });

    if (!exists) {
      await Friend.bulkCreate([
        { playerId: myId, friendId: friendId },
        { playerId: friendId, friendId: myId },
      ]);
      await notificationManager.delete(notificationId, myId);

      await this.broadcastFriendListUpdate(myId);
      await this.broadcastFriendListUpdate(friendId);

      return true;
    }
    return false;
  }

  async getFriendList(playerId) {
    const player = await Player.findByPk(playerId, {
      include: [
        {
          model: Player,
          as: "Friends",
          attributes: ["id", "username", "level"],
        },
      ],
    });
    return player?.Friends || [];
  }

  async broadcastFriendListUpdate(playerId) {
    if (!this.io) return;

    const list = await this.getFriendList(playerId);
    const targetSocket = [...this.io.sockets.sockets.values()].find(
      (s) => s.user?.id === playerId,
    );

    if (targetSocket) {
      targetSocket.emit("friend:list", list);
    }
  }
}

module.exports = new SocialManager();
