/**
 * @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.header("Content-Type", "text/html");
      response.send(`<!DOCTYPE html>
<html>
  <head>
    <title>Tingle Bot</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="description" content="Custom bot for my friend Ruu's Zelda-themed RP server" />
    <script src="https://cdn.nhcarrigan.com/headers/index.js" async defer></script>
  </head>
  <body>
    <main>
    <h1>Tingle Bot</h1>
    <section>
      <p>Custom bot for my friend Ruu's Zelda-themed RP server.</p>
    </section>
    <section>
        <h2>Links</h2>
        <p>
            <a href="https://codeberg.org/nhcarrigan/tingle-bot">
                <i class="fa-solid fa-code"></i> Source Code
            </a>
        </p>
        <p>
            <a href="https://docs.nhcarrigan.com/">
                <i class="fa-solid fa-book"></i> Documentation
            </a>
        </p>
        <p>
            <a href="https://chat.nhcarrigan.com">
                <i class="fa-solid fa-circle-info"></i> Support
            </a>
        </p>
    </section>
    </main>
  </body>
</html>`);
    });

    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");
  }
};
