// /app/api/sign-s3-url/route.ts
import { NextResponse } from "next/server";
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const s3 = 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 } = await req.json(); // key = "path/to/photo.jpg"
    if (!key)
      return NextResponse.json({ error: "Missing key" }, { status: 400 });

    const command = new GetObjectCommand({
      Bucket: process.env.RETROFIT_DATA_DEV_S3_BUCKET_NAME!,
      Key: key,
    });

    // URL expires in 30 minutes
    const signedUrl = await getSignedUrl(s3, 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 });
  }
}
