/**
 * Helpers for building image URLs returned by the Ridoo API.
 */

/**
 * Base URL for API-hosted assets (e.g. `/media/fleet/...`).
 * `NEXT_PUBLIC_API_URL` is optional — fall back to the production API so
 * URLs are never built as "undefined/..." (which crashes `next/image`).
 */
function normalizeBase(raw: string): string {
  const withProtocol = /^https?:\/\//i.test(raw) ? raw : `https://${raw}`;
  return withProtocol.replace(/\/+$/, "");
}

const API_BASE = normalizeBase(
  process.env.NEXT_PUBLIC_API_URL || "https://api.ridoo.co.in"
);

/**
 * Builds a valid `src` for `next/image` from an API image path.
 *
 * - Absolute URLs (`http://…`, `https://`, `//…`) are returned unchanged.
 * - Empty / missing values fall back to a local placeholder in `/public`.
 * - Anything else is treated as API-relative (e.g. `/media/fleet/…`).
 */
export function resolveImageUrl(
  path?: string | null,
  fallback: string = "/logo.png"
): string {
  const src = typeof path === "string" ? path.trim() : "";
  if (!src) return fallback;
  if (src.startsWith("//")) return `https:${src}`;
  if (/^https?:\/\//i.test(src)) return src;
  return `${API_BASE}${src.startsWith("/") ? "" : "/"}${src}`;
}
