import webpush from "web-push";
import PouchDB from "./PouchDB";
import { ServerSettingsDocument } from "@hereconnect/types";

if (!process.env.VAPID_SUBJECT) {
  throw new Error("VAPID_SUBJECT env is empty!");
}

const vapidKeys = webpush.generateVAPIDKeys();

await new PouchDB<ServerSettingsDocument>(
  `${process.env.API_URL}/server_settings`,
  { skip_setup: true },
).put({
  _id: "server_settings:message_delivery_method_web_push_vapid",
  type: "server_settings",
  name: "message_delivery_method_web_push_vapid",
  value: {
    subject: process.env.VAPID_SUBJECT,
    keys: vapidKeys,
  },
  created_at: new Date().toISOString(),
});

await new PouchDB(`${process.env.API_URL}/public_settings`, {
  skip_setup: true,
}).put({
  _id: "public_settings:message_delivery_method_web_push_vapid_public_key",
  type: "public_settings",
  name: "message_delivery_method_web_push_vapid_public_key",
  value: vapidKeys.publicKey,
  created_at: new Date().toISOString(),
});

if (process.env.GCM_API_KEY) {
  await new PouchDB(`${process.env.API_URL}/public_settings`, {
    skip_setup: true,
  }).put({
    _id: "server_settings:message_delivery_method_web_push_gcm_api_key",
    type: "server_settings",
    name: "message_delivery_method_web_push_gcm_api_key",
    value: process.env.GCM_API_KEY,
    created_at: new Date().toISOString(),
  });
}
