"use server";

import { writeFile } from "fs/promises";
import { PLATFORM_MOD_ID, RESTRICT_ACCESS_LIST } from "./constants";
import mongo, {
  Account,
  ChannelInvite,
  createDM,
  fetchAccountById,
  findDM,
} from "./db";
import { publishMessage, sendChatMessage } from "./redis";
import { ulid } from "ulid";
import {
  AccountInfo,
  AccountStrike,
  Bot,
  Channel,
  File,
  Member,
  Message,
  Report,
  Server,
  SessionInfo,
  User,
} from "revolt-api";
import { checkPermission } from "./accessPermissions";
import { Long } from "mongodb";

export async function sendAlert(userId: string, content: string) {
  await checkPermission("users/create/alert", userId, { content });

  const messageId = ulid();

  let dm = await findDM(PLATFORM_MOD_ID, userId);
  if (!dm) dm = await createDM(PLATFORM_MOD_ID, userId, messageId);

  await sendChatMessage({
    _id: messageId,
    author: PLATFORM_MOD_ID,
    channel: dm._id,
    content,
  });
}

export async function createStrike(
  userId: string,
  givenReason: string,
  additionalContext: string
) {
  if (RESTRICT_ACCESS_LIST.includes(userId)) throw "restricted access";

  await checkPermission("users/create/strike", userId, {
    givenReason,
    additionalContext,
  });

  const strike: AccountStrike & { moderator_id: string } = {
    _id: ulid(),
    user_id: userId,
    moderator_id: "01EX2NCWQ0CHS3QJF0FEQS1GR4", // TODO
    reason: additionalContext
      ? givenReason + " - " + additionalContext
      : givenReason,
  };

  await mongo()
    .db("revolt")
    .collection<{ _id: string }>("safety_strikes")
    .insertOne(strike);
  await sendAlert(
    userId,
    `You have received an account strike, for one or more reasons:
- ${givenReason}
 
Further violations will result in suspension or a permanent ban depending on severity, please abide by the [Acceptable Usage Policy](https://revolt.chat/aup).`
  );

  return strike;
}

export async function updateReportNotes(reportId: string, notes: string) {
  await checkPermission("reports/update/notes", reportId, { notes });

  return await mongo()
    .db("revolt")
    .collection<Report>("safety_reports")
    .updateOne(
      { _id: reportId },
      {
        $set: {
          notes,
        },
      }
    );
}

export async function resolveReport(reportId: string) {
  await checkPermission("reports/update/resolve", reportId);

  const $set = {
    status: "Resolved",
    closed_at: new Date().toISOString(),
  } as Report;

  await mongo().db("revolt").collection<Report>("safety_reports").updateOne(
    { _id: reportId },
    {
      $set,
    }
  );

  return $set;
}

export async function rejectReport(reportId: string, reason: string) {
  await checkPermission("reports/update/reject", reportId, { reason });

  const $set = {
    status: "Rejected",
    rejection_reason: reason,
    closed_at: new Date().toISOString(),
  } as Report;

  await mongo().db("revolt").collection<Report>("safety_reports").updateOne(
    { _id: reportId },
    {
      $set,
    }
  );

  return $set;
}

export async function reopenReport(reportId: string) {
  await checkPermission("reports/update/reopen", reportId);

  const $set = {
    status: "Created",
  } as Report;

  await mongo()
    .db("revolt")
    .collection<Report>("safety_reports")
    .updateOne(
      { _id: reportId },
      {
        $set,
        $unset: {
          closed_at: 1,
        } as never,
      }
    );

  return $set;
}

export async function closeReportsByUser(userId: string) {
  await checkPermission("reports/update/bulk-close/by-user", userId);

  return await mongo()
    .db("revolt")
    .collection<Report>("safety_reports")
    .updateMany(
      {
        status: "Created",
        author_id: userId,
      },
      {
        $set: {
          status: "Rejected",
          rejection_reason: "bulk close",
          closed_at: new Date().toISOString(),
        },
      }
    )
    .then((res) => res.modifiedCount);
}

export async function disableAccount(userId: string) {
  if (RESTRICT_ACCESS_LIST.includes(userId)) throw "restricted access";

  await checkPermission("accounts/disable", userId);

  await mongo()
    .db("revolt")
    .collection<AccountInfo>("accounts")
    .updateOne({ _id: userId }, { $set: { disabled: true } });

  await mongo().db("revolt").collection<SessionInfo>("sessions").deleteMany({
    user_id: userId,
  });
}

export async function deleteMFARecoveryCodes(userId: string) {
  if (RESTRICT_ACCESS_LIST.includes(userId)) throw "restricted access";
  await checkPermission("accounts/update/mfa", userId);

  await mongo()
    .db("revolt")
    .collection<Account>("accounts")
    .updateOne(
      { _id: userId },
      {
        $unset: {
          "mfa.recovery_codes": 1,
        },
      },
    )
}

export async function disableMFA(userId: string) {
  if (RESTRICT_ACCESS_LIST.includes(userId)) throw "restricted access";
  await checkPermission("accounts/update/mfa", userId);

  await mongo()
    .db("revolt")
    .collection<Account>("accounts")
    .updateOne(
      { _id: userId },
      {
        $unset: {
          "mfa.totp_token": 1,
        },
      },
    )
}

export async function changeAccountEmail(userId: string, email: string) {
  if (RESTRICT_ACCESS_LIST.includes(userId)) throw "restricted access";
  await checkPermission("accounts/update/email", userId);

  const SPLIT_RE = /([^@]+)(@.+)/;
  const SYMBOL_RE = /\+.+|\./g;

  const segments = SPLIT_RE.exec(email);
  if (!segments) throw "invalid email";

  await mongo()
    .db("revolt")
    .collection<Account>("accounts")
    .updateOne(
      { _id: userId },
      {
        $set: {
          email: email,
          email_normalised: segments[1].replace(SYMBOL_RE, "") + segments[2],
          verification: { status: "Verified" },
        },
      }
    );
}

export async function verifyAccountEmail(userId: string) {
  if (RESTRICT_ACCESS_LIST.includes(userId)) throw "restricted access";
  await checkPermission("accounts/update/email", userId);

  const account = await fetchAccountById(userId);

  if (!account) throw new Error("couldn't find account");
  if (account.verification.status == "Verified")
    throw new Error("already verified");

  let email = account.email;
  if (account.verification.status == "Moving") {
    email = account.verification.new_email;
  }

  await mongo()
    .db("revolt")
    .collection<Account>("accounts")
    .updateOne(
      { _id: userId },
      {
        $set: {
          email: email,
          email_normalised: email, // <-- should be fine but someone should fix this in the future
          verification: { status: "Verified" },
        },
      }
    );
}

export async function lookupEmail(email: string): Promise<string | false> {
  await checkPermission("accounts/fetch/by-email", email);

  const accounts = mongo()
    .db("revolt")
    .collection<Account>("accounts");

  let result = await accounts.findOne({ email: email });
  if (result) return result._id;

  result = await accounts.findOne({ email_normalised: email });
  if (result) return result._id;

  return false;
}

export async function suspendUser(userId: string) {
  if (RESTRICT_ACCESS_LIST.includes(userId)) throw "restricted access";

  await checkPermission("users/action/suspend", userId);
  await disableAccount(userId);

  await mongo()
    .db("revolt")
    .collection<User>("users")
    .updateOne(
      {
        _id: userId,
      },
      {
        $set: {
          flags: 1,
        },
      }
    );

  const memberships = await mongo()
    .db("revolt")
    .collection<{ _id: { user: string; server: string } }>("server_members")
    .find({ "_id.user": userId })
    .toArray();

  for (const topic of memberships.map((x) => x._id.server)) {
    await publishMessage(topic, {
      type: "UserUpdate",
      id: userId,
      data: {
        flags: 1,
      },
      clear: [],
    });
  }
}

export async function updateUserBadges(userId: string, badges: number) {
  await checkPermission("users/update/badges", userId, { badges });
  await mongo().db("revolt").collection<User>("users").updateOne(
    {
      _id: userId,
    },
    {
      $set: {
        badges,
      },
    }
  );

  const memberships = await mongo()
    .db("revolt")
    .collection<{ _id: { user: string; server: string } }>("server_members")
    .find({ "_id.user": userId })
    .toArray();

  for (const topic of [userId, ...memberships.map((x) => x._id.server)]) {
    await publishMessage(topic, {
      type: "UserUpdate",
      id: userId,
      data: {
        badges,
      },
      clear: [],
    });
  }
}

export async function wipeUser(userId: string, flags = 4) {
  if (RESTRICT_ACCESS_LIST.includes(userId)) throw "restricted access";

  await checkPermission("users/action/wipe", userId, { flags });

  const user = await mongo()
    .db("revolt")
    .collection<User>("users")
    .findOne({ _id: userId });

  const messages = await mongo()
    .db("revolt")
    .collection<Message>("messages")
    .find({ author: userId }, { sort: { _id: -1 } })
    .toArray();

  const dms = await mongo()
    .db("revolt")
    .collection<Channel>("channels")
    .find({
      channel_type: "DirectMessage",
      recipients: userId,
    })
    .toArray();

  const memberships = await mongo()
    .db("revolt")
    .collection<{ _id: { user: string; server: string } }>("server_members")
    .find({ "_id.user": userId })
    .toArray();

  // retrieve messages, dm channels, relationships, server memberships
  const backup = {
    _event: "wipe",
    user,
    messages,
    dms,
    memberships,
  };

  await writeFile(
    `./exports/${new Date().toISOString()} - ${userId}.json`,
    JSON.stringify(backup)
  );

  // mark all attachments as deleted + reported
  const attachmentIds = backup.messages
    .filter((message) => message.attachments)
    .map((message) => message.attachments)
    .flat()
    .filter((attachment) => attachment)
    .map((attachment) => attachment!._id);

  if (backup.user?.avatar) {
    attachmentIds.push(backup.user.avatar._id);
  }

  if (backup.user?.profile?.background) {
    attachmentIds.push(backup.user.profile.background._id);
  }

  if (attachmentIds.length) {
    await mongo()
      .db("revolt")
      .collection<File>("attachments")
      .updateMany(
        { _id: { $in: attachmentIds } },
        {
          $set: {
            reported: true,
            deleted: true,
          },
        }
      );
  }

  // delete messages
  await mongo().db("revolt").collection<Message>("messages").deleteMany({
    author: userId,
  });

  // delete server memberships
  await mongo().db("revolt").collection<Member>("server_members").deleteMany({
    "_id.user": userId,
  });

  // disable account
  await disableAccount(userId);

  // clear user profile
  await mongo()
    .db("revolt")
    .collection<User>("users")
    .updateOne(
      {
        _id: userId,
      },
      {
        $set: {
          flags,
        },
        $unset: {
          avatar: 1,
          profile: 1,
          status: 1,
        },
      }
    );

  // broadcast wipe event
  for (const topic of [
    ...backup.dms.map((x) => x._id),
    ...backup.memberships.map((x) => x._id.server),
  ]) {
    await publishMessage(topic, {
      type: "UserPlatformWipe",
      user_id: userId,
      flags,
    });
  }
}

export async function banUser(userId: string) {
  if (RESTRICT_ACCESS_LIST.includes(userId)) throw "restricted access";
  await checkPermission("users/action/ban", userId);
  return await wipeUser(userId, 4);
}

export async function unsuspendUser(userId: string) {
  if (RESTRICT_ACCESS_LIST.includes(userId)) throw "restricted access";
  await checkPermission("users/action/unsuspend", userId);
  await restoreAccount(userId);

  await mongo()
    .db("revolt")
    .collection<User>("users")
    .updateOne(
      {
        _id: userId,
      },
      {
        $unset: {
          flags: 1,
        },
      }
    );
}

export async function wipeUserProfile(
  userId: string,
  fields: {
    banner: boolean;
    avatar: boolean;
    bio: boolean;
    displayName: boolean;
    status: boolean;
  }
) {
  await checkPermission("users/action/wipe-profile", userId);

  await mongo()
    .db("revolt")
    .collection<User>("users")
    .updateOne(
      {
        _id: userId,
      },
      {
        $unset: {
          ...(fields.banner ? { "profile.background": 1 } : {}),
          ...(fields.bio ? { "profile.content": 1 } : {}),
          ...(fields.status ? { "status.text": 1 } : {}),
          ...(fields.avatar ? { avatar: 1 } : {}),
          ...(fields.displayName ? { display_name: 1 } : {}),
        },
      }
    );
}

export async function updateServerFlags(serverId: string, flags: number) {
  await checkPermission("servers/update/flags", serverId, { flags });
  await mongo().db("revolt").collection<Server>("servers").updateOne(
    {
      _id: serverId,
    },
    {
      $set: {
        flags,
      },
    }
  );

  await publishMessage(serverId, {
    type: "ServerUpdate",
    id: serverId,
    data: {
      flags,
    },
    clear: [],
  });
}

export async function updateServerDiscoverability(
  serverId: string,
  state: boolean
) {
  await checkPermission("servers/update/discoverability", serverId, { state });
  await mongo()
    .db("revolt")
    .collection<Server>("servers")
    .updateOne(
      {
        _id: serverId,
      },
      {
        $set: {
          analytics: state,
          discoverable: state,
        },
      }
    );
}

export async function updateServerOwner(serverId: string, userId: string) {
  await checkPermission("servers/update/owner", { serverId, userId });

  await mongo()
    .db("revolt")
    .collection<Server>("servers")
    .updateOne(
      { _id: serverId },
      { $set: { owner: userId } },
    );

  await publishMessage(serverId, {
    type: "ServerUpdate",
    id: serverId,
    data: {
      owner: userId,
    },
    clear: [],
  });
}

export async function addServerMember(serverId: string, userId: string, withEvent: boolean) {
  const server = await mongo()
    .db("revolt")
    .collection<Server>("servers")
    .findOne({ _id: serverId });

  const channels = await mongo()
    .db("revolt")
    .collection<Channel>("channels")
    .find({ server: serverId })
    .toArray();

  if (!server) throw new Error("server doesn't exist");

  await mongo()
    .db("revolt")
    .collection<Member>("server_members")
    .insertOne({
      _id: { server: serverId, user: userId },
      joined_at: Long.fromNumber(Date.now()) as unknown as string,
    });

  await publishMessage(userId, {
    type: "ServerCreate",
    id: serverId,
    channels: channels,
    server: server,
  });

  if (withEvent) {
    await publishMessage(serverId, {
      type: "ServerMemberJoin",
      id: serverId,
      user: userId,
    });
  }
}

export async function deleteInvite(invite: string) {
  await checkPermission("channels/update/invites", invite);

  if (!invite) throw new Error("invite is empty");

  await mongo()
    .db("revolt")
    .collection<ChannelInvite>("channel_invites")
    .deleteOne({ _id: invite });
}

export async function editInvite(invite: string, newInvite: string) {
  await checkPermission("channels/update/invites", { invite, newInvite });

  if (!invite) throw new Error("invite is empty");
  if (!newInvite) throw new Error("new invite is empty");

  const { value } = await mongo()
    .db("revolt")
    .collection<ChannelInvite>("channel_invites")
    .findOneAndDelete({ _id: invite });

  if (!value) throw new Error("invite doesn't exist");

  await mongo()
    .db("revolt")
    .collection<ChannelInvite>("channel_invites")
    .insertOne({ ...value, _id: newInvite });
}

export async function editInviteChannel(invite: string, newChannel: string) {
  await checkPermission("channels/update/invites", { invite, newChannel });

  if (!invite) throw new Error("invite is empty");

  await mongo()
    .db("revolt")
    .collection<ChannelInvite>("channel_invites")
    .updateOne({ _id: invite }, { $set: { channel: newChannel } });
}

export async function createInvite(invite: ChannelInvite) {
  await checkPermission("channels/update/invites", invite);

  await mongo()
    .db("revolt")
    .collection<ChannelInvite>("channel_invites")
    .insertOne(invite);
}

export async function bulkDeleteInvites(invites: string[]) {
  await checkPermission("channels/update/invites", invites);

  await mongo()
    .db("revolt")
    .collection<ChannelInvite>("channel_invites")
    .deleteMany({ _id: { $in: invites } });
}

export async function updateBotDiscoverability(botId: string, state: boolean) {
  await checkPermission("bots/update/discoverability", botId, { state });
  await mongo()
    .db("revolt")
    .collection<Bot>("bots")
    .updateOne(
      {
        _id: botId,
      },
      {
        $set: {
          analytics: state,
          discoverable: state,
        },
      }
    );
}

export async function restoreAccount(accountId: string) {
  if (RESTRICT_ACCESS_LIST.includes(accountId)) throw "restricted access";
  await checkPermission("accounts/restore", accountId);
  await mongo()
    .db("revolt")
    .collection<Account>("accounts")
    .updateOne(
      {
        _id: accountId,
      },
      {
        $unset: {
          disabled: 1,
        },
      }
    );
}

export async function queueAccountDeletion(accountId: string) {
  if (RESTRICT_ACCESS_LIST.includes(accountId)) throw "restricted access";
  await checkPermission("accounts/deletion/queue", accountId);
  const twoWeeksFuture = new Date();
  twoWeeksFuture.setDate(twoWeeksFuture.getDate() + 14);

  const $set: Partial<Account> = {
    disabled: true,
    deletion: {
      status: "Scheduled",
      after: twoWeeksFuture.toISOString(),
    },
  };

  await disableAccount(accountId);
  await mongo().db("revolt").collection<Account>("accounts").updateOne(
    {
      _id: accountId,
    },
    {
      $set,
    }
  );

  return $set;
}

export async function cancelAccountDeletion(accountId: string) {
  if (RESTRICT_ACCESS_LIST.includes(accountId)) throw "restricted access";
  await checkPermission("accounts/deletion/cancel", accountId);
  await mongo()
    .db("revolt")
    .collection<Account>("accounts")
    .updateOne(
      {
        _id: accountId,
      },
      {
        $unset: {
          deletion: 1,
        },
      }
    );
}
