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

export async function onRequestGet(context: RequestContext) {
  const robloxUserReq = await fetch(
    "https://users.roblox.com/v1/usernames/users",
    {
      body: JSON.stringify({
        excludeBannedUsers: false,
        usernames: [context.params.user as string],
      }),
      headers: {
        "content-type": "application/json",
      },
      method: "POST",
    },
  );

  if (!robloxUserReq.ok) {
    console.log(await robloxUserReq.text());
    return jsonError("Failed to resolve username", 500);
  }

  const { data: users }: { data: { [k: string]: any }[] } =
    await robloxUserReq.json();

  if (!users.length) return jsonError("No user found with that name", 400);

  const thumbnailRequest = await fetch(
    `https://thumbnails.roblox.com/v1/users/avatar?format=Png&size=250x250&userIds=${users[0].id}`,
  );

  let banList;

  try {
    banList = (await getBanList(context)).value;
  } catch (e) {
    console.log(e);

    return jsonError("Failed to check current moderation status", 500);
  }

  let current_status = "Unknown";

  const banData = banList[users[0].id];

  if (!banData?.BanType) current_status = "Not Moderated";
  else if (banData.BanType === 1) {
    if (
      banData.hidden_from_leaderboards &&
      banData.serverconfigurator_blacklist
    )
      current_status = "Hidden / Server Config Blocked";
    else if (banData.hidden_from_leaderboards)
      current_status = "Hidden From Leaderboards";
    else if (banData.serverconfigurator_blacklist)
      current_status = "Server Config Blocked";
  } else if (banData.BanType === 2) current_status = "Banned";

  const response = {
    history: await context.data.prisma.gameModLog.findMany({
      orderBy: {
        executed_at: "desc",
      },
      where: {
        target: users[0].id,
      },
    }),
    user: {
      avatar: thumbnailRequest.ok
        ? (
            (await thumbnailRequest.json()) as {
              data: { imageUrl: string }[];
            }
          ).data[0].imageUrl
        : null,
      current_status,
      id: users[0].id,
      name: users[0].name,
    },
  };

  return jsonResponse(JSON.stringify(response));
}
