import webpush from "web-push";
import PouchDB from "./PouchDB.js";

if (!process.env.API_URL) {
  throw new Error(`env API_URL is not set`);
}

const {
  rows: [
    {
      doc: { value: vapidDetails },
    },
    { doc: gcmApiSettingsDoc },
  ],
} = await new PouchDB(`${process.env.API_URL}/server_settings`, {
  skip_setup: true,
}).allDocs({
  keys: [
    "server_settings:message_delivery_method_web_push_vapid",
    "public_settings:message_delivery_method_web_push_gcm_api_key",
  ],
  include_docs: true,
});

webpush.setVapidDetails(
  vapidDetails.subject,
  vapidDetails.keys.publicKey,
  vapidDetails.keys.privateKey,
);

if (gcmApiSettingsDoc) {
  console.log(gcmApiSettingsDoc.value);
  webpush.setGCMAPIKey(gcmApiSettingsDoc.value);
}

// optionally provide an identifier that the push service uses to coalesce notifications
const topic = "chat-6ilhxu-13trvu";

const notification = {
  type: "notification",
  notification: {
    title: "test",
    options: {
      icon: "/images/qr-code-logo-200x200.jpg",
      body: "Test push message from server.",
      tag: "01936062-d10f-7f2f-8ae3-dd7f9fbc5c7f",
      requireInteraction: true,
      // silent: false,
      // vibrate: [200, 100, 200, 100, 200, 100, 200],
      // actions: [
      //   {
      //     action: "open_url",
      //     title: "Открыть",
      //   },
      // ],
      data: {
        url: "/chat/6ilhxu/13trvu",
        payload: { tag: "01936062-d10f-7f2f-8ae3-dd7f9fbc5c7f" },
      },
    },
  },
};

const { rows } = await new PouchDB(
  `${process.env.API_URL}/web_push_subscriptions`,
  { skip_setup: true },
).allDocs(
  process.env.WEB_PUSH_SUBSCRIPTION_ID
    ? {
        key: process.env.WEB_PUSH_SUBSCRIPTION_ID,
        include_docs: true,
      }
    : {
        startkey: "web_push_subscription:",
        endkey: "web_push_subscription:\uFFFF",
        include_docs: true,
      },
);

const result = await Promise.allSettled(
  rows.map(async ({ doc }) => {
    await webpush.sendNotification(
      doc.subscription,
      JSON.stringify(notification),
      {
        urgency: "high",
        topic,
      },
    );
    console.log("sent ", doc._id);
  }),
);
console.log(result);

// issues:
// 1. NO SOUND
// 2. SAFARI NO OPEN PAGE
