import Constants from 'expo-constants';
import * as Localization from 'expo-localization';
import { ParkSmarterClient, type EnvironmentName } from 'parksmarter-client';
import { secureTokenStore } from './secureTokenStore';
import { authBus } from '@/auth/authBus';
import { logLine } from '@/features/diagnostics/fileLogger';

const env =
  (Constants.expoConfig?.extra?.psEnvironment as EnvironmentName) ?? 'prodv2';

/**
 * The single app-wide API client. React Native ships a global `fetch`, so no
 * fetchImpl override is needed. Tokens persist in the OS keystore. On a 401 the
 * client clears the token and we bounce the user to sign-in via authBus.
 */
export const ps = new ParkSmarterClient({
  environment: env,
  tokens: secureTokenStore,
  localeCode: (Localization.getLocales()[0]?.languageCode ?? 'en').toLowerCase(),
  onUnauthorized: () => authBus.onUnauthorized?.(),
  // Redacted request/response logging -> logcat AND the on-device log file (when
  // enabled in Diagnostics). Toggle at runtime with ps.setLogRequests().
  logRequests: Boolean(Constants.expoConfig?.extra?.debugHttp),
  logSink: (line: string) => {
    console.log(line);
    logLine(line);
  },
});
