import { NextResponse } from "next/server";
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const energyAssessmentsS3 = new S3Client({
  region: process.env.PRESIGN_AWS_REGION,
  credentials: {
    accessKeyId: process.env.RETROFIT_ENERGY_ASSESSMENTS_AWS_ACCESS_KEY!,
    secretAccessKey: process.env.ENERGY_ASSESSMENTS_AWS_SECRET!,
  },
});

const retrofitDataS3 = new S3Client({
  region: process.env.RETROFIT_DATA_DEV_REGION,
  credentials: {
    accessKeyId: process.env.RETROFIT_DATA_DEV_ACCESS_KEY!,
    secretAccessKey: process.env.RETROFIT_DATA_DEV_SECRET_KEY!,
  },
});

export async function POST(req: Request) {
  try {
    const { key, bucket } = await req.json();
    if (!key || !bucket)
      return NextResponse.json({ error: "Missing key or bucket" }, { status: 400 });

    const isEnergyAssessments = bucket === process.env.RETROFIT_ENERGY_ASSESSMENTS_BUCKET;
    const s3Client = isEnergyAssessments ? energyAssessmentsS3 : retrofitDataS3;

    const command = new GetObjectCommand({ Bucket: bucket, Key: key });
    const signedUrl = await getSignedUrl(s3Client, command, { expiresIn: 1800 });

    return NextResponse.json({ url: signedUrl });
  } catch (error) {
    console.error("Error generating signed URL:", error);
    return NextResponse.json({ error: "Failed to sign URL" }, { status: 500 });
  }
}
