// pages/api/get-presigned-url.ts
import S3 from "aws-sdk/clients/s3";
import STS from "aws-sdk/clients/sts"; // Import STS for temporary credentials
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

// Validate the input
const PresignedUrlBodySchema = z.object({
  fileKey: z.string(),
});

// Function to get temporary credentials using GetSessionToken
async function getTemporaryCredentials() {
  const sts = new STS({
    accessKeyId: process.env.RETROFIT_ENERGY_ASSESSMENTS_AWS_ACCESS_KEY, // Your permanent access key
    secretAccessKey: process.env.ENERGY_ASSESSMENTS_AWS_SECRET, // Your permanent secret access key
    region: process.env.PRESIGN_AWS_REGION,
  });

  try {
    // Request temporary credentials with GetSessionToken
    const data = await sts.getSessionToken({ DurationSeconds: 900 }).promise(); // Token valid for 15 minutes

    // Check if credentials are present
    if (!data.Credentials) {
      throw new Error("Failed to retrieve temporary credentials");
    }

    return data.Credentials;
  } catch (error) {
    console.error("Error fetching temporary credentials:", error);
    throw error;
  }
}

// API handler
export async function POST(request: NextRequest) {
  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 {
    // Get temporary credentials using GetSessionToken
    const credentials = await getTemporaryCredentials();

    // Initialize S3 with temporary credentials
    const s3 = new S3({
      signatureVersion: "v4",
      region: process.env.PRESIGN_AWS_REGION,
      accessKeyId: credentials.AccessKeyId,
      secretAccessKey: credentials.SecretAccessKey,
      sessionToken: credentials.SessionToken, // Include session token
    });

    const { fileKey } = validatedBody;

    // Generate presigned URL valid for 5 minutes
    const preSignedUrl = await s3.getSignedUrl("getObject", {
      Bucket: process.env.RETROFIT_ENERGY_ASSESSMENTS_BUCKET,
      Key: fileKey,
      Expires: 5 * 60, // URL expiration in seconds
    });

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