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

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

  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);

  const item: Record<string, any> | null = await context.env.D1.prepare(
    `SELECT *
     FROM ${types[type].table}
     WHERE id = ?;`,
  )
    .bind(itemId)
    .first();

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

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

  if (item.user) {
    item.user = JSON.parse(item.user);

    delete item.user.email;
  }

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