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

export async function onRequestGet(context: RequestContext) {
  const { id, type } = context.params;

  if (!["appeal", "inactivity", "report"].includes(type as string))
    return jsonError("Invalid type", 400);

  const data = (await context.env.DATA.get(`${type}_${id}`, {
    type: "json",
  })) as {
    created_at: number;
    id: string;
    open: boolean;
    user?: { id: string; username: string };
  } & { [k: string]: any };

  if (type === "report") {
    let resolvedUrls = [];
    let signingPromises = [];
    const key = await crypto.subtle.importKey(
      "raw",
      Uint8Array.from(atob(context.env.URL_SIGNING_KEY), (c) =>
        c.charCodeAt(0),
      ),
      { hash: "SHA=256", name: "HMAC" },
      false,
      ["sign"],
    );

    const exp = Math.round(Date.now() / 1000) + 1800;

    for (const attachment of data.attachments) {
      const unsignedUrl = `https://mediaproxy.carcrushers.cc/${attachment}?Expires=${exp}&KeyName=portal-media-linkgen`;
      signingPromises.push(
        crypto.subtle.sign("HMAC", key, new TextEncoder().encode(unsignedUrl)),
      );
    }

    let signatures: ArrayBuffer[];

    try {
      signatures = await Promise.all(signingPromises);
    } catch (e) {
      console.log(e);

      return jsonError("Failed to create signed links", 500);
    }

    for (let i = 0; i < signatures.length; i++) {
      resolvedUrls.push(
        `https://mediaproxy.carcrushers.cc/${
          data.attachments[i]
        }?Expires=${exp}&KeyName=portal-media-linkgen&Signature=${btoa(
          String.fromCharCode(...new Uint8Array(signatures[i]))
            .replaceAll("+", "-")
            .replaceAll("/", "_")
            .replaceAll("=", ""),
        )}`,
      );
    }

    data.resolved_attachments = resolvedUrls;
  }

  if (!data?.user?.id !== context.data.current_user.id)
    return jsonError("Item does not exist", 404);

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