/**
 * @copyright nhcarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */

import { readFile } from "node:fs/promises";
import { type Client, WebhookClient } from "discord.js";
import fastify from "fastify";
import { errorHandler } from "../utils/errorHandler.js";

/**
 * Starts up a web server for health monitoring.
 * @param bot - The bot's Discord instance.
 */
export const instantiateServer = async(bot: Client) => {
  try {
    const server = fastify({
      https: {
        cert: await readFile(
          "/etc/letsencrypt/live/ruubot.nhcarrigan.com/cert.pem",
        ),
        key: await readFile(
          "/etc/letsencrypt/live/ruubot.nhcarrigan.com/privkey.pem",
        ),
      },
      logger: false,
    });

    server.get("/", (_request, response) => {
      response.send("Health check~!");
    });

    server.listen({ port: 4443 }, (error) => {
      if (error) {
        void errorHandler(error, "start server");
        return;
      }
      const hook = new WebhookClient({ url: process.env.DEBUG_HOOK as string });
      void hook.send({
        avatarURL:
          bot.user?.displayAvatarURL()
          ?? "https://cdn.nhcarrigan.com/profile.png",
        content:  "Fastify server live on port 1443~!",
        username: bot.user?.username ?? "Boost Monitor",
      });
    });
  } catch (error) {
    await errorHandler(error, "instantiate server");
  }
};
