import { IdentityClient } from './identity';
import { EResidencyClient } from './eresidency';
import { IntakeClient } from './intake';
import { FinanceClient } from './finance';
import { DataroomClient } from './dataroom';

export class ApiClient {
  public readonly identity: IdentityClient;
  public readonly eresidency: EResidencyClient;
  public readonly intake: IntakeClient;
  public readonly finance: FinanceClient;
  public readonly dataroom: DataroomClient;

  constructor(baseURL?: string) {
    // Initialize service clients - each manages its own axios instance
    this.identity = new IdentityClient(baseURL);
    this.eresidency = new EResidencyClient(baseURL);
    this.intake = new IntakeClient(baseURL);
    this.finance = new FinanceClient(baseURL);
    this.dataroom = new DataroomClient(baseURL);
  }

  setAuthToken(token: string): void {
    if (typeof window !== 'undefined') {
      localStorage.setItem('auth_token', token);
    }
    // Update all service clients
    this.identity.setAuthToken(token);
    this.eresidency.setAuthToken(token);
    this.intake.setAuthToken(token);
    this.finance.setAuthToken(token);
    this.dataroom.setAuthToken(token);
  }

  clearAuth(): void {
    // Clear tokens in all service clients
    this.identity.clearAuthToken();
    this.eresidency.clearAuthToken();
    this.intake.clearAuthToken();
    this.finance.clearAuthToken();
    this.dataroom.clearAuthToken();
  }
}

// Singleton instance
let apiClientInstance: ApiClient | null = null;

export function getApiClient(): ApiClient {
  if (!apiClientInstance) {
    apiClientInstance = new ApiClient();
  }
  return apiClientInstance;
}
