import { jsonError, jsonResponse } from "../../../common.js";

export async function onRequestGet(context: RequestContext) {
  const types: { [k: string]: { permissions: number[]; prefix: string } } = {
    appeal: {
      permissions: [1 << 0, 1 << 1],
      prefix: `appeal_`,
    },
    gma: {
      permissions: [1 << 5],
      prefix: "gameappeal_",
    },
    inactivity: {
      permissions: [1 << 0, 1 << 4, 1 << 6, 1 << 7, 1 << 11],
      prefix: "inactivity_",
    },
    report: {
      permissions: [1 << 5],
      prefix: "report_",
    },
  };

  const type = context.params.type as string;
  const itemId = context.params.id as string;

  if (
    !types[type]?.permissions.find(
      (p) => context.data.current_user.permissions & p,
    )
  )
    return jsonError("You cannot use this filter", 403);

  let item: {
    [k: string]: any;
  } | null = await context.env.DATA.get(`${types[type].prefix}${itemId}`, {
    type: "json",
  });

  if (!item)
    item = await context.env.DATA.get(`closed${types[type].prefix}${itemId}`, {
      type: "json",
    });

  if (
    type === "report" &&
    (await context.env.DATA.get(`reportprocessing_${itemId}`))
  )
    return jsonError("Report is processing", 409);

  if (item) delete item.user?.email;

  return item
    ? jsonResponse(JSON.stringify(item))
    : jsonError("Not found", 404);
}
