import { createS3Client } from "@/app/utils/s3";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

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

export async function POST(request: NextRequest) {
  let body;
  try {
    body = BodySchema.parse(await request.json());
  } catch (error) {
    console.error("Invalid input:", error);
    return NextResponse.json({ error: "Invalid input" }, { status: 400 });
  }

  try {
    const s3 = createS3Client();

    const preSignedUrl = await s3.getSignedUrlPromise("putObject", {
      Bucket: process.env.RETROFIT_PLAN_INPUT_BUCKET_NAME,
      Key: body.fileKey,
      ContentType: body.contentType,
      Expires: 5 * 60,
    });

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