/**
 * Notification Model
 * Handles notification operations
 */

const { query } = require("../config/database");

class Notification {
  /**
   * Create notification
   */
  static async create(notificationData) {
    const result = await query(
      `INSERT INTO notifications (user_id, title, message, type, reference_type, reference_id)
             VALUES (?, ?, ?, ?, ?, ?)`,
      [
        notificationData.userId,
        notificationData.title,
        notificationData.message,
        notificationData.type || "General",
        notificationData.referenceType || null,
        notificationData.referenceId || null,
      ],
    );

    return { id: result.insertId, ...notificationData };
  }

  /**
   * Create notifications for multiple users
   */
  static async createBulk(userIds, notificationData) {
    const values = userIds.map((userId) => [
      userId,
      notificationData.title,
      notificationData.message,
      notificationData.type || "General",
      notificationData.referenceType || null,
      notificationData.referenceId || null,
    ]);

    if (values.length === 0) return [];

    const placeholders = values.map(() => "(?, ?, ?, ?, ?, ?)").join(", ");
    const flatValues = values.flat();

    await query(
      `INSERT INTO notifications (user_id, title, message, type, reference_type, reference_id)
             VALUES ${placeholders}`,
      flatValues,
    );

    return true;
  }

  /**
   * Get notifications for user
   */
  static async findByUser(userId, options = {}) {
    const { limit = 20, unreadOnly = false } = options;

    let whereClause = "user_id = ?";
    const params = [userId];

    if (unreadOnly) {
      whereClause += " AND is_read = FALSE";
    }

    return query(
      `SELECT * FROM notifications 
             WHERE ${whereClause}
             ORDER BY created_at DESC
             LIMIT ?`,
      [...params, limit],
    );
  }

  /**
   * Mark notification as read
   */
  static async markAsRead(id, userId) {
    await query(
      "UPDATE notifications SET is_read = TRUE WHERE id = ? AND user_id = ?",
      [id, userId],
    );
    return true;
  }

  /**
   * Mark all notifications as read for user
   */
  static async markAllAsRead(userId) {
    await query(
      "UPDATE notifications SET is_read = TRUE WHERE user_id = ? AND is_read = FALSE",
      [userId],
    );
    return true;
  }

  /**
   * Get unread count for user
   */
  static async getUnreadCount(userId) {
    const result = await query(
      "SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = FALSE",
      [userId],
    );
    return result[0].count;
  }

  /**
   * Delete old notifications
   */
  static async deleteOld(days = 30) {
    await query(
      "DELETE FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)",
      [days],
    );
    return true;
  }
}

module.exports = Notification;
