import { API_PREFIX, IS_PRODUCTION, PUBLIC_API_URL } from "../config/environment";

/**
 * Build a default Stripe Connect callback URL on the API itself.
 *
 * Why the API (not the frontend) should be the default:
 *  - Stripe redirects from its hosted onboarding page back to `return_url` in the
 *    user's *system browser*. That browser has no JWT — the token lives in the
 *    mobile app's storage, not the device-wide browser. Pointing `return_url` at
 *    a JWT-gated frontend page therefore lands the user on an "Authentication
 *    Required" prompt.
 *  - The API exposes public landing handlers (no JWT) at:
 *      GET  /api/v1/user/stripe/return        (alias: /wallet/stripe/return)
 *      GET  /api/v1/user/stripe/refresh       (alias: /wallet/stripe/refresh)
 *      GET  /api/v1/gas-stations/stripe/return
 *      GET  /api/v1/gas-stations/stripe/refresh
 *    They sync the user's Stripe Connect status using the `uid` query param the
 *    API auto-appends, then render a friendly "you can close this page" screen.
 *
 * Returns null if PUBLIC_API_URL is not configured — caller should treat that as
 * a server-side configuration error.
 */
export function buildDefaultStripeConnectUrl(
  pathSuffix: "/user/stripe/return" | "/user/stripe/refresh"
    | "/gas-stations/stripe/return" | "/gas-stations/stripe/refresh"
): string | null {
  if (!PUBLIC_API_URL) return null;
  return `${PUBLIC_API_URL}${API_PREFIX}${pathSuffix}`;
}

/**
 * Stripe requires HTTPS for `account_links.return_url` / `refresh_url` in live mode
 * (and in test mode for hosted onboarding). Reject http:// in production so we fail
 * fast with a clear message instead of getting an opaque Stripe error.
 */
export function assertHttpsIfProduction(rawUrl: string, fieldName: string): void {
  if (!IS_PRODUCTION) return;
  let parsed: URL;
  try {
    parsed = new URL(rawUrl);
  } catch {
    throw new Error(`${fieldName} is not a valid URL`);
  }
  if (parsed.protocol !== "https:") {
    throw new Error(`${fieldName} must use https:// in production (got ${parsed.protocol})`);
  }
}
