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

const Schema = z.object({
  path: z.string(),
  expiresInSeconds: z.number().int().positive().default(300),
  contentType: z.string(),
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { path, expiresInSeconds, contentType } =
      Schema.parse(body);

    // Retrofit s3 bucket connection
    let bucket = process.env.RETROFIT_ENERGY_ASSESSMENTS_BUCKET
    // let bucket = process.env.RETROFIT_PLAN_INPUT_BUCKET_NAME
    if (!bucket) {
      return NextResponse.json({ msg: "RETROFIT_ENERGY_ASSESSMENTS_BUCKET is not set" }, { status: 400 });
    }

    const s3 = createS3Client({
      region: process.env.PRESIGN_AWS_REGION,
      accessKeyId: process.env.RETROFIT_ENERGY_ASSESSMENTS_AWS_ACCESS_KEY,
      secretAccessKey: process.env.RETROFIT_ENERGY_ASSESSMENTS_AWS_SECRET,
    });



    const url = await presignGetUrl(s3, {
      bucket,
      key: path,
      expiresInSeconds,
      ContentType: contentType,
    });

    return NextResponse.json({ url });
  } catch (err) {
    console.error(err);
    return err instanceof z.ZodError
      ? NextResponse.json({ msg: "Invalid input", issues: err.issues }, { status: 400 })
      : NextResponse.json({ msg: "Internal server error" }, { status: 500 });
  }
}


