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 tables: { [k: string]: string } = {
    appeal: "appeals",
    inactivity: "inactivity_notices",
    report: "reports",
  };

  const data: Record<string, any> | null = await context.env.D1.prepare(
    `SELECT *
                                                                         FROM ${tables[type as string]}
                                                                         WHERE id = ?;`,
  )
    .bind(id)
    .first();

  if (data?.user) data.user = JSON.parse(data.user);

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

  if (type === "report") {
    data.attachments = JSON.parse(data.attachments);
    const { AwsClient } = await import("aws4fetch");
    const aws = new AwsClient({
      accessKeyId: context.env.R2_ACCESS_KEY,
      secretAccessKey: context.env.R2_SECRET_KEY,
    });

    let urls = [];

    for (const attachment of data.attachments) {
      const { url } = await aws.sign(
        `https://car-crushers.${context.env.R2_ZONE}.r2.cloudflarestorage.com/${attachment}?X-Amz-Expires=1800`,
        {
          aws: {
            signQuery: true,
          },
        },
      );

      urls.push(url);
    }

    data.resolved_attachments = urls;
  }

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