// Push notifications to browsers: the page subscribes with the server's VAPID public key,
// and the server sends to each subscription it kept.
//
//   VAPID_PRIVATE_KEY=... quillo run web_push.qwe      then open http://localhost:8080/vapid
//   (without it a key is made at start: subscriptions then last until the next restart)

use "web_push.qwer"

let VAPID = env("VAPID_PRIVATE_KEY", null) ?? webpush_vapid_keys().private_key
let SUBJECT = "mailto:ops@example.com"

// What a browser's pushManager.subscribe() gave, kept in the database in a real app.
// SINK_URL is a stand-in push service, for tests.
let subscriptions = [{
    endpoint: `${env("SINK_URL", "https://fcm.googleapis.com/fcm/send")}/push/c1Xb2`,
    keys: { p256dh: "BALaTKCMXVvGeD-NJCngShS8dmT0QqytfjB4VrfrVd9dKIEVn6oi_t5vpxR1Df8LS6hBX2q3zlT1DNsPvnjWeFw", auth: "_33LOyr359zokWB60AyCIg" },
}]

// For the page: navigator.serviceWorker.ready.then((r) => r.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key }))
route GET /vapid = { key: webpush_public_key(VAPID)? }

route GET /notify ? { text: str = "Your order has shipped" } {
    let sent = subscriptions | map((s) => webpush_send(s, json.stringify({ title: "Shop", body: text, url: "/orders" }), VAPID, SUBJECT, 3600)?)
    { sent: len(sent), statuses: sent | map((r) => r.status), ended: len(filter(sent, (r) => r.gone)) }
}
