import { CapacitorHttp } from "@capacitor/core";
import { isNativeApp } from "@/native/nativePlayer";

export const proxyFetch = async <T = unknown>(
  url: string,
  responseType: "json" | "text" = "json"
): Promise<T> => {
  // الاتصال المباشر فوراً لضمان السرعة وتجاوز البروكسي
  if (isNativeApp() || url.startsWith('http')) {
    const res = await CapacitorHttp.request({
      url,
      method: "GET",
      headers: {
        "User-Agent": "PurplePlayer/3.34.0 (Linux; Android 12)",
        "Accept": responseType === "json" ? "application/json, */*" : "*/*",
      },
      responseType: responseType === "text" ? "text" : "json",
      connectTimeout: 8000,
      readTimeout: 15000,
    });

    if (res.status < 200 || res.status >= 300) {
      throw new Error(`Connection Error: ${res.status}`);
    }

    if (responseType === "text") return String(res.data) as T;
    return (typeof res.data === "string" ? JSON.parse(res.data) : res.data) as T;
  }
  
  // مسار الويب الاحتياطي (Fallback)
  const res = await fetch(url); 
  return (responseType === "text" ? await res.text() : await res.json()) as T;
};
