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

export async function onRequestPost(context: RequestContext) {
  const { statsReduction } = context.data.body;

  if (statsReduction && typeof statsReduction !== "number")
    return jsonError("Invalid stat reduction", 400);

  const appeal = await context.data.prisma.gameAppeal.findUnique({
    select: {
      roblox_id: true,
      type: true,
    },
    where: {
      id: context.params.id as string,
    },
  });

  if (!appeal) return jsonError("Appeal not found", 400);

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

  await context.data.prisma.gameAppeal.delete({
    where: {
      id: context.params.id as string,
    },
  });

  if (!banList[appeal.roblox_id]?.BanType)
    return new Response(null, {
      status: 204,
    });

  if (banList[appeal.roblox_id].BanType === 2) {
    banList[appeal.roblox_id] = {
      BanType: 0,
      Unbanned: true,
      UnbanReduct: statsReduction,
    };
  } else if (appeal.type === "server configurator") {
    banList[appeal.roblox_id] = {
      ...banList[appeal.roblox_id],
      serverconfigurator_blacklist: false,
    };
  } else if (appeal.type === "blacklist") {
    banList[appeal.roblox_id] = {
      ...banList[appeal.roblox_id],
      hidden_from_leaderboards: false,
      Unbanned: true,
      UnbanReduct: statsReduction,
    };
  }

  await context.data.prisma.gameModLog.create({
    data: {
      action: `accept appeal | ${banList[appeal.roblox_id]?.BanType === 2 ? "ban" : appeal.type}`,
      evidence: `https://carcrushers.cc/mod-queue?id=${context.params.id}&type=gma`,
      executor: context.data.current_user.id,
      id: crypto.randomUUID(),
      target: appeal.roblox_id,
    },
  });

  await setBanList(context, banList, etag);

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