// models/pushSubscriptionModel.js const { getDb } = require('../dbPool'); const pushSubscriptionModel = { async subscribe(userId, subscription) { const db = await getDb(); const { endpoint, keys } = subscription; await db.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 db = await getDb(); await db.query('DELETE FROM push_subscriptions WHERE endpoint = ?', [endpoint]); }, async getByUserId(userId) { const db = await getDb(); const [rows] = await db.query( 'SELECT * FROM push_subscriptions WHERE user_id = ?', [userId] ); return rows; }, async getByUserIds(userIds) { if (!userIds || userIds.length === 0) return []; const db = await getDb(); const [rows] = await db.query( 'SELECT * FROM push_subscriptions WHERE user_id IN (?)', [userIds] ); return rows; }, async getAll() { const db = await getDb(); const [rows] = await db.query('SELECT * FROM push_subscriptions'); return rows; }, async deleteByEndpoint(endpoint) { const db = await getDb(); await db.query('DELETE FROM push_subscriptions WHERE endpoint = ?', [endpoint]); }, // === ntfy 구독 관련 === async getNtfyUserIds(userIds) { if (!userIds || userIds.length === 0) return []; const db = await getDb(); const [rows] = await db.query( 'SELECT user_id FROM ntfy_subscriptions WHERE user_id IN (?)', [userIds] ); return rows.map(r => r.user_id); }, async getAllNtfyUserIds() { const db = await getDb(); const [rows] = await db.query('SELECT user_id FROM ntfy_subscriptions'); return rows.map(r => r.user_id); }, async ntfySubscribe(userId) { const db = await getDb(); await db.query( 'INSERT IGNORE INTO ntfy_subscriptions (user_id) VALUES (?)', [userId] ); }, async ntfyUnsubscribe(userId) { const db = await getDb(); await db.query('DELETE FROM ntfy_subscriptions WHERE user_id = ?', [userId]); }, async isNtfySubscribed(userId) { const db = await getDb(); const [rows] = await db.query( 'SELECT 1 FROM ntfy_subscriptions WHERE user_id = ? LIMIT 1', [userId] ); return rows.length > 0; } }; module.exports = pushSubscriptionModel;