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 user = await context.env.DATA.get(`reportprocessing_${id}`);

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

  await context.env.DATA.delete(`reportprocessing_${id}`);

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

  if (!value) return jsonError("Report is missing", 500);

  const coconutData = (await context.env.DATA.get(`coconutdata_${id}`, {
    type: "json",
  })) as {
    attachments: string[];
  } | null;

  if (coconutData) {
    const responsePromises = [];

    for (const attachment of coconutData.attachments) {
      const token = crypto.randomUUID();

      responsePromises.push(
        fetch("https://api.coconut.co/v2/jobs", {
          body: JSON.stringify({
            input: {
              bucket: "car-crushers",
              credentials: {
                access_key_id: context.env.R2_ACCESS_KEY,
                secret_access_key: context.env.R2_SECRET_KEY,
              },
              endpoint: `https://${context.env.R2_ZONE}.r2.cloudflarestorage.com`,
              key: `/t/${attachment}`,
              region: "us-east-1",
              service: "s3other",
            },
            notification: {
              params: {
                attachment,
                token,
              },
              type: "http",
              url: `https://${context.request.headers.get("host")}/api/coconut`,
            },
            outputs: {
              mp4: {
                format: {
                  level: 20,
                  metadata: 0,
                  quality: 4,
                  vprofile: "high",
                },
                path: `/${attachment}.mp4`,
              },
            },
            storage: {
              bucket: "car-crushers",
              credentials: {
                access_key_id: context.env.R2_ACCESS_KEY,
                secret_access_key: context.env.R2_SECRET_KEY,
              },
              endpoint: `https://${context.env.R2_ZONE}.r2.cloudflarestorage.com`,
              region: "us-east-1",
              service: "s3other",
            },
          }),
          headers: {
            authorization: `Basic ${btoa(`${context.env.COCONUT_API_KEY}:`)}`,
            "content-type": "application/json",
          },
          method: "POST",
        }),
        await context.env.DATA.put(`coconutjob_${attachment}`, token, {
          expirationTtl: 600,
        }),
      );
    }

    const resolvedPromises = await Promise.allSettled(responsePromises);

    for (const p of resolvedPromises) {
      if (p.status === "rejected")
        console.log(`Request to coconut failed: ${p}`);
      else {
        if (p.value && !p.value.ok)
          console.log(`Request rejected by coconut: ${await p.value.text()}`);
      }
    }

    await context.env.DATA.delete(`coconutdata_${id}`);
  }

  if (context.env.REPORTS_WEBHOOK) {
    await fetch(context.env.REPORTS_WEBHOOK, {
      body: JSON.stringify({
        embeds: [
          {
            title: "Report Submitted",
            color: 3756250,
            description: `View this report at https://carcrushers.cc/mod-queue?id=${id}&type=report`,
          },
        ],
      }),
      headers: {
        "content-type": "application/json",
      },
      method: "POST",
    });
  }

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