/**
 * Singleton factory for the AppGate client.  Credentials come from env vars
 * and the client is lazily instantiated.  Matches the pattern used for
 * `autotask-factory.ts`, `msgraph-factory.ts`, etc.
 *
 * Env vars:
 *   APPGATE_URL            base controller URL, e.g. https://wawnvaagp01.wulfconsulting.com:8443
 *   APPGATE_USERNAME       service-user account name
 *   APPGATE_PASSWORD       service-user password
 *   APPGATE_PROVIDER_NAME  identity provider used for that account (default 'local')
 *   APPGATE_DEVICE_ID      stable UUID identifying Pulse as an API client
 *   APPGATE_INSECURE_TLS   "false" to disable the self-signed cert bypass
 */

import { AppgateClient } from './appgate-client';

let _client: AppgateClient | null = null;

export function isAppgateConfigured(): boolean {
  return Boolean(
    process.env.APPGATE_URL &&
    process.env.APPGATE_USERNAME &&
    process.env.APPGATE_PASSWORD &&
    process.env.APPGATE_DEVICE_ID,
  );
}

export function getAppgateClient(): AppgateClient {
  if (_client) return _client;
  if (!isAppgateConfigured()) {
    throw new Error('AppGate is not configured — set APPGATE_URL, APPGATE_USERNAME, APPGATE_PASSWORD, APPGATE_DEVICE_ID');
  }
  _client = new AppgateClient({
    baseUrl:      process.env.APPGATE_URL!,
    username:     process.env.APPGATE_USERNAME!,
    password:     process.env.APPGATE_PASSWORD!,
    providerName: process.env.APPGATE_PROVIDER_NAME ?? 'local',
    deviceId:     process.env.APPGATE_DEVICE_ID!,
    insecureTls:  process.env.APPGATE_INSECURE_TLS !== 'false',
  });
  return _client;
}

// Test seam — reset the cached client (e.g. after rotating credentials).
export function _resetAppgateClient(): void {
  _client = null;
}
