import { initializeAPI, getValidToken } from '../core/api';
import { TokenResponse } from './types';

type Config = {
  baseUrl?: string;
  tenantId?: string;
  apiKey?: string;
  getToken?: () => Promise<TokenResponse>;
};

class ConfigService {
  private static instance: ConfigService;
  private config: Config | null = null;

  private constructor() {}

  static getInstance(): ConfigService {
    if (!ConfigService.instance) {
      ConfigService.instance = new ConfigService();
    }
    return ConfigService.instance;
  }

  initialize(config: Config) {
    this.config = {
      baseUrl: config.baseUrl || 'https://babylai.net/api',
      tenantId: config.tenantId,
      apiKey: config.apiKey,
      getToken: config.getToken,
    };

    // Initialize API with the getToken function directly
    if (!this.config.getToken) {
      throw new Error('getToken function is required in configuration');
    }

    initializeAPI(this.config.baseUrl || 'https://babylai.net/api', this.config.getToken);
  }

  getConfig(): Config {
    if (!this.config) {
      throw new Error('Help Center not initialized. Call initialize() first with configuration.');
    }
    return this.config;
  }

  async getToken(): Promise<string> {
    return await getValidToken();
  }
}

export const configService = ConfigService.getInstance();
