const zulip = require("zulip-js");

export async function deleteMessagesZulip(streamName, topicName, numOfDay) {
  const config = {
    zuliprc: "./download",
    zulipVersion: "v2",
  };
  const client = await zulip(config);
  try {
    const messages = await client.messages.retrieve({
      anchor: "oldest",
      num_before: 0,
      num_after: 5000,
      narrow: [
        { operator: "stream", operand: streamName },
        { operator: "topic", operand: topicName },
      ],
    });
    // console.log(messages.messages.map(u=>u.reactions))
    const members = await client.users.retrieve();

    // console.log(members.members)
    for (const message of messages.messages) {
      if (
        message.reactions.filter(
          (i) =>
            i.emoji_name === "working_on_it" &&
            members.members.filter((u) => u.user_id === i.user_id)[0]
              .is_admin === true
        ).length === 0 &&
        message.timestamp <
          Math.floor((Date.now() - 60000 * 60 * 24 * numOfDay) / 1000)
      ) {
        const res = await client.messages.deleteById({
          message_id: message.id,
        });
        console.log(`Deleted message ID ${message.id}`);
        // console.log(res)
      }
    }
  } catch (error) {
    console.error("Error:", error);
  }
}
