// models/pushSubscriptionModel.js
const { getPool } = require('./userModel');

const pushSubscriptionModel = {
  async subscribe(userId, subscription) {
    const pool = getPool();
    const { endpoint, keys } = subscription;
    await pool.query(
      `INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth)
       VALUES (?, ?, ?, ?)
       ON DUPLICATE KEY UPDATE user_id = VALUES(user_id), p256dh = VALUES(p256dh), auth = VALUES(auth)`,
      [userId, endpoint, keys.p256dh, keys.auth]
    );
  },

  async unsubscribe(endpoint) {
    const pool = getPool();
    await pool.query('DELETE FROM push_subscriptions WHERE endpoint = ?', [endpoint]);
  },

  async getByUserId(userId) {
    const pool = getPool();
    const [rows] = await pool.query(
      'SELECT * FROM push_subscriptions WHERE user_id = ?',
      [userId]
    );
    return rows;
  },

  async getByUserIds(userIds) {
    if (!userIds || userIds.length === 0) return [];
    const pool = getPool();
    const [rows] = await pool.query(
      'SELECT * FROM push_subscriptions WHERE user_id IN (?)',
      [userIds]
    );
    return rows;
  },

  async getAll() {
    const pool = getPool();
    const [rows] = await pool.query('SELECT * FROM push_subscriptions');
    return rows;
  },

  async deleteByEndpoint(endpoint) {
    const pool = getPool();
    await pool.query('DELETE FROM push_subscriptions WHERE endpoint = ?', [endpoint]);
  },

  // === ntfy 구독 관련 ===

  async getNtfyUserIds(userIds) {
    if (!userIds || userIds.length === 0) return [];
    const pool = getPool();
    const [rows] = await pool.query(
      'SELECT user_id FROM ntfy_subscriptions WHERE user_id IN (?)',
      [userIds]
    );
    return rows.map(r => r.user_id);
  },

  async getAllNtfyUserIds() {
    const pool = getPool();
    const [rows] = await pool.query('SELECT user_id FROM ntfy_subscriptions');
    return rows.map(r => r.user_id);
  },

  async ntfySubscribe(userId) {
    const pool = getPool();
    await pool.query(
      'INSERT IGNORE INTO ntfy_subscriptions (user_id) VALUES (?)',
      [userId]
    );
  },

  async ntfyUnsubscribe(userId) {
    const pool = getPool();
    await pool.query('DELETE FROM ntfy_subscriptions WHERE user_id = ?', [userId]);
  },

  async isNtfySubscribed(userId) {
    const pool = getPool();
    const [rows] = await pool.query(
      'SELECT 1 FROM ntfy_subscriptions WHERE user_id = ? LIMIT 1',
      [userId]
    );
    return rows.length > 0;
  }
};

module.exports = pushSubscriptionModel;
