"use server";

import { createClient } from "redis";
import { Channel, Message } from "revolt-api";
import type { ProtocolV1 } from "revolt.js/lib/events/v1";
import mongo from "./db";
import { checkPermission } from "./accessPermissions";

let client: ReturnType<typeof createClient>;

async function redis() {
  if (!client) {
    client = createClient({
      url: process.env.REDIS!,
    });

    await client.connect();
  }

  return client;
}

export default redis;

export async function publishMessage(
  topic: string,
  message: ProtocolV1["server"]
) {
  await checkPermission("publish_message", topic, { message });
  return await (await redis()).publish(topic, JSON.stringify(message));
}

export async function sendChatMessage(message: Message, ephermal = false) {
  await checkPermission("chat_message", message.channel, { message, ephermal });

  if (!ephermal) {
    await mongo()
      .db("revolt")
      .collection<Message>("messages")
      .insertOne(message);

    await mongo()
      .db("revolt")
      .collection<Channel>("channels")
      .updateOne(
        { _id: message.channel },
        { $set: { last_message_id: message._id } }
      );
  }

  await publishMessage(message.channel, {
    type: "Message",
    ...message,
  });
}
