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

export async function POST(req: NextRequest) {
  try {
    const { storage_path, expiresInSeconds = 120 } = await req.json();
    if (!storage_path || typeof storage_path !== "string") {
      return NextResponse.json({ error: "missing_storage_path" }, { status: 400 });
    }
  // If caller sent a full URL already, return it as-is
  if (/^https?:\/\//.test(storage_path)) {
    return NextResponse.json({ url: storage_path });
  }

  // Try raw key, then try stripping a leading slash
  let url = await getS3SignedUrlIfExists(storage_path, expiresInSeconds);
  if (!url && storage_path.startsWith("/")) {
    url = await getS3SignedUrlIfExists(storage_path.replace(/^\//, ""), expiresInSeconds);
  }
  if (!url) {
    return NextResponse.json({ error: 'not_found', message: 'Fichier introuvable' }, { status: 404 });
  }
  return NextResponse.json({ url });
  } catch (err: any) {
    return NextResponse.json({ error: err?.message || "server_error" }, { status: 500 });
  }
}
