// reusing from refbounty: 
// https://gitea.chromart.cc/martin/refbounty/src/commit/1f40d7870a530fe7e7acbc3b901024092c9fb90a/packages/server/src/connectors/DiscordConnector.ts
// https://gitea.chromart.cc/martin/refbounty/src/commit/1f40d7870a530fe7e7acbc3b901024092c9fb90a/packages/server/src/utils/DiscordUtils.ts

import { Client, GatewayIntentBits, User } from "discord.js";
import { TwilioContext } from "../types/TwilioContext";

let conn: Client;
let userCache: Record<string, User> = {};

export const getDiscordClient = async (context: TwilioContext) => {
  if (!conn) {
    console.log("[DiscordClientCache] cache miss for discord");
    const client = new Client({
      intents: [GatewayIntentBits.DirectMessages],
      rest: {
        timeout: 60_000, // 60s
      }
    });

    await client.login(context.DISCORD_BOT_TOKEN);
    conn = client;
  } else {
    console.log("[DiscordClientCache] cache hit for discord");
  }

  return conn;
};


export const sendMessageToUser = async (
  context: TwilioContext,
  userId: string,
  msg: string,
) => {
  const client = await getDiscordClient(context);
  if (userCache[userId] === undefined) {
    console.log("[UserCache] cache miss for", userId);
    userCache[userId] = await client.users.fetch(userId);
  } else {
    console.log("[UserCache] cache hit for", userId);
  }
  const user = userCache[userId];
  return user.send(msg);
};

export const jsonMsgSuffix = (jsonString: string = "") => {
  if (!jsonString) {
    return "";
  }
  try {
    const fingerprint = JSON.parse(jsonString);
    return `\`\`\`# Unlocked by\n${JSON.stringify(fingerprint, null, 4)}\`\`\``;
  } catch (e) {
    return `\`\`\`# Unlocked by\n# WARN: Unknown or corrupt raw fingerprint:\n ${jsonString}\`\`\``;
  }
};
