import S3 from "aws-sdk/clients/s3";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

const presignedUrlSchema = z.object({
  files: z.array(
    z.object({
      fileKey: z.string(),
      contentType: z.string(),
    })
  ),
});

export async function POST(request: NextRequest) {
  const body = await request.json();
  let validatedBody;

  try {
    validatedBody = presignedUrlSchema.parse(body);
  } catch (error) {
    console.error("Invalid input: ", error);
    return new NextResponse(JSON.stringify({ msg: "Invalid input" }), {
      status: 400,
    });
  }

  console.log("UPLOAD BODY", validatedBody);

  try {
    const s3 = new S3({
      signatureVersion: "v4",
      region: process.env.DUE_CONSIDERATIONS_AWS_REGION,
      accessKeyId: process.env.DUE_CONSIDERATIONS_AWS_ACCESS_KEY,
      secretAccessKey: process.env.DUE_CONSIDERATIONS_AWS_SECRET_KEY,
    });

    const { files } = validatedBody;
    // generate a presigned URL for each file
    const preSignedUrls = await Promise.all(
      files.map(async (file: any) => {
        return s3.getSignedUrlPromise("putObject", {
          Bucket: process.env.DUE_CONSIDERATIONS_BUCKET,
          Key: file.fileKey,
          ContentType: file.contentType,
          Expires: 5 * 60,
        });
      })
    );

    return new NextResponse(JSON.stringify({ urls: preSignedUrls }), {
      status: 200,
    });
  } catch (error) {
    console.error(error);
    return new NextResponse(JSON.stringify({ msg: "Internal server error" }), {
      status: 500,
    });
  }
}
