import { NextRequest, NextResponse } from "next/server";
import { getSignedUrlForKey } from "@/lib/s3-upload";

/**
 * GET /api/images/signed-url?key=avatars/user123/avatar.jpg
 * Generate signed URL for S3 objects
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const key = searchParams.get("key");
    const expiresIn = parseInt(searchParams.get("expiresIn") || "3600");

    if (!key) {
      return NextResponse.json(
        { error: "S3 key is required" },
        { status: 400 }
      );
    }

    // Validate expiresIn range (1 minute to 7 days)
    if (expiresIn < 60 || expiresIn > 604800) {
      return NextResponse.json(
        { error: "expiresIn must be between 60 and 604800 seconds" },
        { status: 400 }
      );
    }

    const signedUrl = await getSignedUrlForKey(key, expiresIn);

    return NextResponse.json({
      url: signedUrl,
      expiresIn,
      expiresAt: new Date(Date.now() + expiresIn * 1000).toISOString(),
    });
  } catch (error) {
    console.error("Error generating signed URL:", error);
    return NextResponse.json(
      { error: "Failed to generate signed URL" },
      { status: 500 }
    );
  }
}
