const Notification = require("../models/Notification");

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

  init(io) {
    this.io = io;
    console.log("[NotificationManager] Initialized with Socket.io");
  }

  async send({
    playerId,
    type = "info",
    title,
    message,
    data = {},
    priority = "normal",
  }) {
    try {
      const notification = await Notification.create({
        playerId,
        type,
        title,
        message,
        data,
        priority,
        isRead: false,
      });

      const targetSocket = this._getSocketByPlayerId(playerId);

      if (targetSocket) {
        targetSocket.emit("notification:new", notification);

        const unreadCount = await this.getUnreadCount(playerId);
        targetSocket.emit("notifications:unread_count", unreadCount);
      }

      return notification;
    } catch (error) {
      console.error(
        `[NotificationManager] Error sending to ${playerId}:`,
        error,
      );
    }
  }

  _getSocketByPlayerId(playerId) {
    if (!this.io) return null;
    return [...this.io.sockets.sockets.values()].find(
      (s) => s.user?.id === playerId,
    );
  }
  async getPlayerHistory(playerId, limit = 50) {
    return await Notification.findAll({
      where: { playerId },
      order: [["createdAt", "DESC"]],
      limit,
    });
  }

  async getUnreadCount(playerId) {
    return await Notification.count({
      where: { playerId, isRead: false },
    });
  }

  async markAsRead(notificationId, playerId) {
    await Notification.update(
      { isRead: true },
      { where: { id: notificationId, playerId } },
    );
    return await this.getUnreadCount(playerId);
  }

  async markAllAsRead(playerId) {
    await Notification.update(
      { isRead: true },
      { where: { playerId, isRead: false } },
    );
    return 0;
  }

  async delete(notificationId, playerId) {
    await Notification.destroy({
      where: { id: notificationId, playerId },
    });
    return await this.getUnreadCount(playerId);
  }
}

module.exports = new NotificationManager();
