import { getBanList, setBanList } from "../../../roblox-open-cloud.js";
import { jsonError } from "../../../common.js";

export async function onRequestPost(context: RequestContext) {
  if (!(context.data.current_user.permissions & (1 << 5)))
    return jsonError("Forbidden", 403);

  const { ticket_link } = context.data.body;

  if (
    !ticket_link?.match(
      /^https?:\/\/carcrushers\.modmail\.dev\/logs\/[a-z\d]{12}$/,
    )
  )
    return jsonError("Invalid ticket link provided", 400);

  const user = context.params.user as string;

  if (isNaN(parseInt(user))) return jsonError("Invalid user ID", 400);

  await context.data.prisma.gameModLog.create({
    data: {
      action: "revoke",
      evidence: ticket_link,
      executor: context.data.current_user.id,
      id: crypto.randomUUID(),
      target: parseInt(user),
    },
  });

  const { etag, value: banList } = await getBanList(context);

  delete banList[user];
  await setBanList(context, banList, etag);

  return new Response(null, {
    status: 204,
  });
}
