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

const PresignedUrlBodySchema = z.object({
  userId: z.string(),
  portfolioId: z.string(),
  fileKey: z.string(),
});

export async function POST(request: NextRequest) {
  // For the moment, this api specifically handles uploads of csvs

  const body = await request.json();
  let validatedBody;

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

  try {
    const s3 = new S3({
      signatureVersion: "v4",
      region: process.env.PRESIGN_AWS_REGION,
      accessKeyId: process.env.PRESIGN_AWS_ACCESS_KEY,
      secretAccessKey: process.env.PRESIGN_AWS_SECRET_KEY,
    });

    const { fileKey } = validatedBody;

    console.log("Making presigned URL")
    // Presigned url is valid for 5 minutes
    const preSignedUrl = await s3.getSignedUrl("putObject", {
      Bucket: process.env.RETROFIT_PLAN_INPUT_BUCKET_NAME,
      Key: fileKey,
      ContentType: "text/csv",
      Expires: 5 * 60,
    });
    console.log("preSignedUrl:", preSignedUrl)

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