/**
 * resolveUploadUrl — normalise stored upload paths to absolute URLs.
 *
 * The local storage backend previously returned relative paths like
 * "/uploads/banner/abc.webp".  These resolve against the Next.js origin
 * (port 3000), not the FastAPI backend (port 8000), causing broken images.
 *
 * The backend now returns absolute URLs (http://localhost:8000/uploads/...)
 * but documents already saved in MongoDB may still have the old relative form.
 * This helper handles both so no data migration is needed.
 *
 * Usage:
 *   import { resolveUploadUrl } from "@/lib/uploadUrl";
 *   <Image src={resolveUploadUrl(url)} ... />
 */

const BACKEND = (
  process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000"
).replace(/\/$/, "");

export function resolveUploadUrl(url: string | null | undefined): string {
  if (!url) return "";
  // Absolute URL — rewrite localhost origins to the configured backend so
  // images uploaded in dev still work when the frontend is served from a
  // different origin in production.
  if (url.startsWith("http://") || url.startsWith("https://")) {
    try {
      const parsed = new URL(url);
      if (parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1") {
        return `${BACKEND}${parsed.pathname}${parsed.search}`;
      }
    } catch {
      // Malformed URL — fall through and return as-is
    }
    return url;
  }
  // Legacy relative path produced by old LocalStorageBackend config
  if (url.startsWith("/uploads/")) return `${BACKEND}${url}`;
  // Any other relative path — return as-is
  return url;
}
