/**
 * Generates an imgproxy URL for a given source image and options.
 *
 * Documentation: https://docs.imgproxy.net/usage/processing
 */

interface ImgproxyOptions {
  width?: number;
  height?: number;
  resizing_type?: "fit" | "fill" | "fill-down" | "force" | "auto";
  gravity?: string;
  enlarge?: boolean;
  extension?: string;
}

/**
 * Encodes a string to Base64 (URL-safe)
 */
function encodeBase64(str: string): string {
  if (typeof Buffer !== "undefined") {
    return Buffer.from(str)
      .toString("base64")
      .replace(/\+/g, "-")
      .replace(/\//g, "_")
      .replace(/=+$/, "");
  } else {
    // Fallback for browser environment if Buffer is not available
    return window
      .btoa(str)
      .replace(/\+/g, "-")
      .replace(/\//g, "_")
      .replace(/=+$/, "");
  }
}

export function getImgproxyUrl(
  src: string,
  options: ImgproxyOptions = {},
): string {
  const baseUrl =
    process.env.NEXT_PUBLIC_IMGPROXY_URL || "https://img.infra.mintel.me";

  // If no imgproxy URL is configured, return the source as is
  if (!baseUrl) return src;

  // Handle local paths or relative URLs
  let absoluteSrc = src;
  if (src.startsWith("/")) {
    const baseUrlForSrc =
      process.env.NEXT_PUBLIC_BASE_URL ||
      (typeof window !== "undefined" ? window.location.origin : "");
    if (baseUrlForSrc) {
      absoluteSrc = `${baseUrlForSrc}${src}`;
    }
  }

  // Development mapping: Map local domains to internal Docker hostnames
  // so imgproxy can fetch images without SSL issues or external routing
  if (process.env.NODE_ENV === "development") {
    if (absoluteSrc.includes("mintel.localhost")) {
      absoluteSrc = absoluteSrc.replace(
        /^https?:\/\/mintel\.localhost/,
        "http://app:3000",
      );
    } else if (absoluteSrc.includes("cms.mintel.localhost")) {
      absoluteSrc = absoluteSrc.replace(
        /^https?:\/\/cms\.mintel\.localhost/,
        "http://directus:8055",
      );
    }
    console.log(`[imgproxy] ${src} -> ${absoluteSrc}`);
  }

  const {
    width = 0,
    height = 0,
    resizing_type = "fit",
    gravity = "sm", // Default to smart gravity
    enlarge = false,
    extension = "",
  } = options;

  // Processing options
  // Format: /rs:<type>:<width>:<height>:<enlarge>/g:<gravity>
  const processingOptions = [
    `rs:${resizing_type}:${width}:${height}:${enlarge ? 1 : 0}`,
    `g:${gravity}`,
  ].join("/");

  // Using /unsafe/ for now as we don't handle signatures yet
  // Format: <base_url>/unsafe/<options>/<base64_url>
  const suffix = extension ? `@${extension}` : "";
  const encodedSrc = encodeBase64(absoluteSrc + suffix);

  return `${baseUrl}/unsafe/${processingOptions}/${encodedSrc}`;
}
