import webpush from 'web-push';
export class PushService {
    db;
    enabled;
    constructor(db, env) {
        this.db = db;
        this.enabled = Boolean(env.VAPID_PUBLIC_KEY && env.VAPID_PRIVATE_KEY);
        if (this.enabled)
            webpush.setVapidDetails(env.VAPID_SUBJECT, env.VAPID_PUBLIC_KEY, env.VAPID_PRIVATE_KEY);
    }
    async sendToWarehouse(warehouseId, payload) {
        if (!this.enabled)
            return;
        const users = await this.db.query(`SELECT DISTINCT u.id FROM users u JOIN user_roles ur ON ur.user_id = u.id JOIN roles r ON r.id = ur.role_id
       WHERE r.code = 'warehouse_operator' AND u.warehouse_id = $1 AND u.active = true AND u.archived_at IS NULL`, [warehouseId]);
        await Promise.all(users.rows.map((user) => this.sendToUser(user.id, payload)));
    }
    async sendToUser(userId, payload) {
        if (!this.enabled)
            return;
        const subscriptions = await this.db.query(`SELECT id, endpoint, p256dh, auth FROM web_push_subscriptions WHERE user_id = $1`, [userId]);
        await Promise.all(subscriptions.rows.map(async (subscription) => {
            try {
                await webpush.sendNotification({
                    endpoint: subscription.endpoint,
                    keys: { p256dh: subscription.p256dh, auth: subscription.auth }
                }, JSON.stringify(payload), { TTL: 300, urgency: 'high' });
            }
            catch (error) {
                const status = error.statusCode;
                if (status === 404 || status === 410)
                    await this.db.query('DELETE FROM web_push_subscriptions WHERE id = $1', [subscription.id]);
            }
        }));
    }
}
//# sourceMappingURL=push-service.js.map