// Wraps a stream URL so playback requests go through the IPTV proxy.
// This bypasses CORS issues that prevent <video>/HLS.js from loading IPTV
// streams directly.
//
// Bypass rules (player uses native HTTP, no CORS, sets UA itself):
//   • Capacitor Android / iOS  → ExoPlayer / AVPlayer
//   • Samsung Tizen TV         → webapis.avplay
//   • LG webOS TV              → HTML5 <video> backed by UMS
//
// All other contexts (web preview, dev) hit the cPanel proxy at
// `${VITE_BACKEND_URL}/api/iptv-proxy?url=…&ua=…` so CORS rules from
// cors.php apply.
import { Capacitor } from "@capacitor/core";
import { getUserAgent } from "@/lib/userAgent";
import { proxyEndpoint } from "@/lib/proxyEndpoint";
import { isSmartTV } from "@/native/tvPlatform";

/** Check if the admin has globally disabled the stream proxy. */
const isProxyDisabled = (): boolean => {
  try {
    const raw = localStorage.getItem("nadiplay_proxy_enabled");
    if (raw !== null) return raw === "false";
  } catch { /* noop */ }
  return false; // default: proxy on
};

export const proxiedStreamUrl = (url: string): string => {
  if (!url) return url;
  if (Capacitor.isNativePlatform()) return url; // ExoPlayer / AVPlayer
  if (isSmartTV()) return url;                  // Tizen AVPlay / webOS UMS
  if (isProxyDisabled()) return url;            // Admin toggled proxy OFF
  // Forward the user's chosen UA so IPTV servers that gate on it (e.g.
  // IPTVSmarters, VLC-only) accept our request.
  const ua = encodeURIComponent(getUserAgent());
  return `${proxyEndpoint()}?url=${encodeURIComponent(url)}&ua=${ua}`;
};
