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

export async function onRequestGet(context: RequestContext) {
  const { searchParams } = new URL(context.request.url);
  const before = parseInt(searchParams.get("before") || `${Date.now()}`);
  const entryType = searchParams.get("type");
  const showClosed = searchParams.get("showClosed") === "true";
  const tables: { [k: string]: string } = {
    appeal: "appeals",
    gma: "game_appeals",
    inactivity: "inactivity_notices",
    report: "reports",
  };
  const types: { [k: string]: string } = {
    appeal: "appeal",
    gma: "gameappeal",
    inactivity: "inactivity",
    report: "report",
  };
  const permissions: { [k: string]: number[] } = {
    appeal: [1 << 0, 1 << 1],
    gma: [1 << 5],
    inactivity: [1 << 4, 1 << 6, 1 << 7, 1 << 11, 1 << 12],
    report: [1 << 5],
  };
  const { current_user: currentUser } = context.data;

  if (!entryType || !types[entryType])
    return jsonError("Invalid filter type", 400);

  if (!permissions[entryType].find((p) => currentUser.permissions & p))
    return jsonError("You cannot use this filter", 403);

  if (isNaN(before)) return jsonError("Invalid `before` parameter", 400);

  const prefix = types[entryType];
  const table = tables[entryType];
  const items = [];
  const { results }: { results?: { created_at: number; id: string }[] } =
    /*
      This is normally VERY BAD and can lead to injection attacks
      However, there is no other way to do this, as using bindings for table names is unsupported apparently
      To avoid any potential injection attacks we enforce a list of specific values and permissions for table names
    */
    await context.env.D1.prepare(
      `SELECT id
       FROM ${table}
       WHERE created_at < ? AND open = ?
       ORDER BY created_at DESC LIMIT 25;`,
    )
      .bind(before, Number(!showClosed))
      .all();

  if (results)
    for (const { id } of results) {
      const item: { [k: string]: any } | null = await context.env.DATA.get(
        `${prefix}_${id}`,
        {
          type: "json",
        },
      );

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

        if (entryType === "inactivity") {
          // Only include inactivity notices that a user can actually act on
          const departments = {
            DM: [1 << 11],
            ET: [1 << 4, 1 << 12],
            FM: [1 << 7],
            WM: [1 << 6],
          };

          if (
            !Object.entries(departments).find(
              (dept) =>
                item.departments.includes(dept[0]) &&
                dept[1].find((p) => currentUser.permissions & p),
            )
          )
            continue;
        }

        items.push({ ...item, id });
      }
    }

  return jsonResponse(JSON.stringify(items.filter((v) => v !== null)));
}
