/**
 * @copyright nhcarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */
import { EmbedBuilder, WebhookClient } from "discord.js";
import { v4 } from "uuid";
import { logHandler } from "./logHandler.js";

/**
 * Formats an error into an embed and sends it to the developer debug webhook.
 * @param error - The error instance from Node.
 * @param context - A description of where the error occurred.
 * @returns The UUID tied to the error.
 */
export const errorHandler = async(
  error: unknown,
  context: string,
): Promise<string> => {
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
  const typedError = error as Error;
  logHandler.log("error", `There was an error in the ${context}:`);
  logHandler.log(
    "error",
    JSON.stringify(
      { errorMessage: typedError.message, errorStack: typedError.stack },
      null,
      2,
    ),
  );

  const errorId = v4();

  const errorEmbed = new EmbedBuilder();
  errorEmbed.setTitle(`RuuBot had a ${context} error!`);
  errorEmbed.setColor(0xFF_00_00);
  errorEmbed.setDescription(typedError.message.slice(0, 4000));
  errorEmbed.addFields([
    { name:  "Stack Trace",
      value: typedError.stack?.slice(0, 1000) ?? "No stack trace available." },
    { name: "Error ID", value: errorId },
  ]);
  errorEmbed.setTimestamp();

  const webhook = new WebhookClient({ url: process.env.DEBUG_HOOK ?? "" });

  await webhook.send({ embeds: [ errorEmbed ] });

  return `The ${context} logic had an error. Please contact the developer with this ID: \`${errorId}\``;
};
