"use strict";var __importDefault=this&&this.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(exports,"__esModule",{value:!0});exports.WebPushProvider=void 0;const web_push_1=__importDefault(require("web-push")),BasePushProvider_1=require("./BasePushProvider");class WebPushProvider extends BasePushProvider_1.BasePushProvider{constructor(i){super("WebPush",i);this.isInitialized=!1;this.validateConfig()&&this.initializeVapid()}loadConfigFromEnv(){return{publicKey:process.env.VAPID_PUBLIC_KEY,privateKey:process.env.VAPID_PRIVATE_KEY,subject:process.env.VAPID_SUBJECT||`mailto:${process.env.APP_NODEMAILER_SMTP_SENDER||"admin@example.com"}`}}validateConfig(){if(!this.config.publicKey){this.logError("Missing VAPID_PUBLIC_KEY",{});return!1}if(!this.config.privateKey){this.logError("Missing VAPID_PRIVATE_KEY",{});return!1}if(!this.config.subject){this.logError("Missing VAPID_SUBJECT",{});return!1}return!0}initializeVapid(){try{web_push_1.default.setVapidDetails(this.config.subject,this.config.publicKey,this.config.privateKey);this.isInitialized=!0}catch(i){this.logError("Failed to initialize VAPID",i);throw i}}async send(i,t){try{if(!this.validateConfig()||!this.isInitialized)throw new Error("WebPush VAPID configuration is invalid or not initialized");const e=this.parseSubscriptions(i.tokens);if(0===e.length)return{success:!1,error:"No valid web push subscriptions provided"};const s=this.buildWebPushPayload(i,t);return await this.sendMulticastInternal(e,s,i)}catch(i){this.logError("Failed to send web push notification",i);return{success:!1,error:i.message||"Failed to send web push notification"}}}async sendToSubscription(i,t,e){try{const s={TTL:e.ttl||("high"===e.priority?300:86400),urgency:"high",headers:{}},r=await web_push_1.default.sendNotification(i,t,s);return{success:!0,messageId:`webpush-${Date.now()}`,metadata:{statusCode:r.statusCode}}}catch(t){if(410===t.statusCode||404===t.statusCode)return{success:!1,error:"Subscription expired",metadata:{invalidSubscription:i.endpoint,shouldRemove:!0,statusCode:t.statusCode}};throw t}}async sendMulticast(i,t,e){const s=this.parseSubscriptions(i),r=this.buildWebPushPayload(t,e);return this.sendMulticastInternal(s,r,t)}async sendMulticastInternal(i,t,e){const s=await Promise.allSettled(i.map(i=>this.sendToSubscription(i,t,e)));let r=0,o=0;const n=[];s.forEach((t,e)=>{var s;if("fulfilled"===t.status&&t.value.success)r++;else{o++;"fulfilled"===t.status&&(null===(s=t.value.metadata)||void 0===s?void 0:s.shouldRemove)&&n.push(i[e].endpoint)}});return{success:r>0,messageId:`webpush-multicast-${Date.now()}`,metadata:{totalSent:i.length,successCount:r,failureCount:o,invalidSubscriptions:n}}}buildWebPushPayload(i,t){var e,s,r;const o={title:this.truncateText(i.title,65),body:this.truncateText(i.body,240),icon:(null===(e=null==t?void 0:t.web)||void 0===e?void 0:e.icon)||i.icon||"/img/logo/android-chrome-192x192.png",badge:(null===(s=null==t?void 0:t.web)||void 0===s?void 0:s.badge)||"/img/logo/android-icon-96x96.png",tag:i.tag,data:{...i.data,url:i.clickAction},requireInteraction:"high"===i.priority,silent:!1};i.imageUrl&&(o.image=i.imageUrl);(null===(r=null==t?void 0:t.web)||void 0===r?void 0:r.vibrate)&&(o.vibrate=t.web.vibrate);o.actions=[{action:"open",title:"Open"},{action:"dismiss",title:"Dismiss"}];return JSON.stringify(o)}parseSubscriptions(i){const t=[];for(const e of i)try{const i=JSON.parse(e);this.isValidSubscription(i)&&t.push(i)}catch(i){}return t}isValidSubscription(i){return i&&"string"==typeof i.endpoint&&i.endpoint.startsWith("https://")&&i.keys&&"string"==typeof i.keys.p256dh&&"string"==typeof i.keys.auth}validateToken(i){try{const t=JSON.parse(i);return this.isValidSubscription(t)}catch(i){return!1}}static generateVapidKeys(){const i=web_push_1.default.generateVAPIDKeys();return{publicKey:i.publicKey,privateKey:i.privateKey}}getPublicKey(){return this.config.publicKey||null}}exports.WebPushProvider=WebPushProvider;