import { buildServerUrl, isNativeApp } from "./server-config";

/**
 * Redirect the user to the OAuth login endpoint.
 *
 * Web: full page redirect to /auth/login; server redirects back after OAuth.
 * Native: Capacitor BridgeWebViewClient intercepts navigation to external host
 * and opens it via Intent.ACTION_VIEW (full Chrome), not Custom Tabs.
 *
 * @param {string} returnTo — path/URL to return to after OAuth
 */
export function redirectToOAuth(returnTo) {
  const url = buildServerUrl(
    `/auth/login?return_to=${encodeURIComponent(returnTo)}`
  );
  window.location.href = url;
}

/**
 * Redirect to the app login page.
 * Used when a 401 is received and we need to force re-authentication.
 */
export function redirectToLoginPage() {
  window.location.href = "/#/login";
}

/**
 * Determine the appropriate OAuth return_to value based on platform.
 * - Web: current page URL (so server redirects back exactly where we were)
 * - Native: /auth/mobile-bridge (server page that fires intent:// back to app)
 * @returns {string}
 */
export function getOAuthReturnTo() {
  if (isNativeApp()) {
    return "/auth/mobile-bridge";
  }
  return window.location.href;
}
