import { GetAccessToken } from "../../gcloud.js";
import { jsonError } from "../../common.js";

export async function onRequestPost(context: RequestContext) {
  const { id } = context.data.body;

  if (!id) return jsonError("No ID provided", 400);

  const reportUserId = await context.env.DATA.get(`reportprocessing_${id}`);

  if (
    !reportUserId ||
    (context.data.current_user?.id !== reportUserId &&
      context.request.headers.get("CF-Connecting-IP") !== reportUserId)
  )
    return jsonError("No processing report with that ID found", 404);

  const data = await context.data.prisma.report.findUnique({
    select: {
      attachments: true,
    },
    where: {
      id,
    },
  });

  if (!data) return jsonError("No report with that ID found", 404);

  const accessToken = await GetAccessToken(context.env);
  const attachmentDeletePromises = [];
  const existingAttachments = [...(data.attachments as string[])];

  for (let i = 0; i < existingAttachments.length; i++) {
    if (!existingAttachments[i].startsWith("t/"))
      existingAttachments[i] = existingAttachments[i].replace("t/", "");
  }

  for (const attachment of existingAttachments)
    attachmentDeletePromises.push(
      fetch(
        `https://storage.googleapis.com/storage/v1/b/portal-carcrushers-cc/o/${encodeURIComponent(
          attachment,
        )}`,
        {
          headers: {
            authorization: `Bearer ${accessToken}`,
          },
          method: "DELETE",
        },
      ),
    );

  await Promise.allSettled(attachmentDeletePromises);
  await context.data.prisma.report.delete({
    where: {
      id,
    },
  });

  return new Response(null, {
    status: 204,
  });
}
