import { Capacitor } from "@capacitor/core";
import { storage } from "./storage";

const SERVER_URL_KEY = "shserv_server_url";

let _currentBaseUrl = "";

/**
 * Detect if running inside a Capacitor native app (Android/iOS).
 * Returns false in a regular browser or PWA.
 */
export function isNativeApp() {
  return Capacitor.isNativePlatform();
}

/**
 * Get the synchronous current base URL (set during app init).
 */
export function getCurrentBaseUrl() {
  return _currentBaseUrl;
}

/**
 * Set the in-memory base URL (used by http.js synchronously).
 */
export function setCurrentBaseUrl(url) {
  _currentBaseUrl = String(url || "").replace(/\/+$/, "");
}

/**
 * Load server URL from native Preferences (or env fallback for web).
 * Call once during app startup.
 */
export async function initServerUrl() {
  if (!isNativeApp()) {
    setCurrentBaseUrl(import.meta.env.VITE_API_BASE_URL || "");
    return;
  }

  try {
    const value = await storage.get(SERVER_URL_KEY);
    setCurrentBaseUrl(value || "");
  } catch {
    setCurrentBaseUrl("");
  }
}

/**
 * Save the server URL for native app use.
 */
export async function setServerUrl(url) {
  const clean = String(url || "").replace(/\/+$/, "");
  setCurrentBaseUrl(clean);

  if (!isNativeApp()) {
    return;
  }

  try {
    await storage.set(SERVER_URL_KEY, clean);
  } catch {
    // ignore
  }
}

/**
 * Build an absolute URL to the server given a path.
 * In web builds (same-origin) returns the path as-is.
 * In native apps prepends the configured server URL.
 */
export function buildServerUrl(path) {
  const base = getCurrentBaseUrl();
  if (!base) {
    return path;
  }
  const cleanPath = String(path || "").replace(/^\/+/, "");
  return cleanPath ? `${base}/${cleanPath}` : base;
}

/**
 * Check if native app has a configured server URL.
 */
export async function hasServerUrl() {
  if (!isNativeApp()) {
    return true;
  }
  // If the in-memory value is already set (e.g. after setServerUrl), trust it
  // so we don't rely on storage round-trip which can race with WebView reload.
  if (_currentBaseUrl) {
    return true;
  }
  const value = await storage.get(SERVER_URL_KEY);
  return !!value;
}
