const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8001/api";

function getApiOrigin() {
  try {
    return new URL(API_BASE).origin;
  } catch {
    return "http://localhost:8001";
  }
}

function ensureLeadingSlash(value: string) {
  return value.startsWith("/") ? value : `/${value}`;
}

export function resolveAssetUrl(path?: string | null): string {
  if (!path) {
    return "";
  }

  if (/^https?:\/\//i.test(path)) {
    try {
      const parsed = new URL(path);
      if (
        typeof window !== "undefined" &&
        (parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1")
      ) {
        parsed.hostname = window.location.hostname;
        return parsed.toString();
      }
      // Uploads saved via Next admin upload route live in frontend /public/uploads.
      // If an absolute backend URL points to /uploads, serve it from local app path.
      if (parsed.pathname.startsWith("/uploads/")) {
        return parsed.pathname;
      }
      return path;
    } catch {
      return path;
    }
  }

  const normalizedPath = ensureLeadingSlash(path);

  if (normalizedPath.startsWith("/media/")) {
    return `${getApiOrigin()}${normalizedPath}`;
  }

  if (normalizedPath.startsWith("/uploads/")) {
    return normalizedPath;
  }

  if (normalizedPath.startsWith("/images/")) {
    return normalizedPath;
  }

  if (normalizedPath.startsWith("/api/")) {
    return normalizedPath;
  }

  if (normalizedPath.startsWith("/")) {
    return `${getApiOrigin()}${normalizedPath}`;
  }

  return normalizedPath;
}
