import { jsonError, jsonResponse } from "../../../common.js";
import { type JsonObject } from "../../../../generated/prisma/internal/prismaNamespace.js";

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

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

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

  let item;

  switch (type) {
    case "appeal":
      item = await context.data.prisma.appeal.findUnique({
        where: {
          id: itemId,
        },
      });

      if (item) delete (item.user as JsonObject).email;
      break;

    case "gma":
      item = await context.data.prisma.gameAppeal.findUnique({
        where: {
          id: itemId,
        },
      });
      break;

    case "inactivity":
      item = await context.data.prisma.inactivityNotice.findUnique({
        where: {
          id: itemId,
        },
      });

      if (item) delete (item.user as JsonObject).email;
      break;

    case "report":
      item = await context.data.prisma.report.findUnique({
        where: {
          id: itemId,
        },
      });

      if (item) delete (item.user as JsonObject | null)?.email;
      break;

    default:
      return jsonError("Unknown filter", 400);
  }

  if (!item) return jsonError("Item not found", 404);

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

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