import { jsonError, jsonResponse } from "../../../../common.js";
import {
  type JsonArray,
  type JsonObject,
} from "../../../../../generated/prisma/internal/prismaNamespace.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 { prisma } = context.data;
  let item;

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

      break;

    case "inactivity":
      item = await prisma.inactivityNotice.findUnique({
        where: {
          id: id as string,
        },
      });

      break;
    case "report":
      item = await prisma.report.findUnique({
        where: {
          id: id as string,
        },
      });

      if (!item) break;

      const { AwsClient } = await import("aws4fetch");
      const aws = new AwsClient({
        accessKeyId: context.env.R2_ACCESS_KEY,
        secretAccessKey: context.env.R2_SECRET_KEY,
      });
      let urlPromises = [];
      for (const attachment of item.attachments as JsonArray) {
        urlPromises.push(
          aws.sign(
            `https://car-crushers.${context.env.R2_ZONE}.r2.cloudflarestorage.com/${attachment}?X-Amz-Expires=1800`,
            {
              aws: {
                signQuery: true,
              },
            },
          ),
        );
      }
      const urls = (await Promise.all(urlPromises)).map((p) => p.url);
      item = { ...item, resolved_attachments: urls };

      break;

    default:
      break;
  }

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

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