import { BASE_URL } from "../config/environment";

/**
 * Build an absolute URL for a stored image value.
 *
 * - Full http(s) URLs (including R2 public URLs) are returned unchanged.
 * - Legacy local paths under `/uploads` or `/public/uploads` resolve via BASE_URL.
 * - "" / null / undefined → null
 */
export function buildImageUrl(image?: string | null): string | null {
  if (!image || typeof image !== "string") return null;
  const trimmed = image.trim();
  if (!trimmed) return null;
  if (/^https?:\/\//i.test(trimmed)) return trimmed;
  if (!BASE_URL) return trimmed;
  const base = BASE_URL.replace(/\/+$/, "");

  let relative = trimmed.replace(/^\/+/, "");
  if (relative.toLowerCase().startsWith("public/")) {
    relative = relative.slice("public/".length);
  }
  if (relative.toLowerCase().startsWith("uploads/")) {
    relative = relative.slice("uploads/".length);
  }

  return `${base}/public/uploads/${relative}`;
}
