import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';

export interface RuntimeConfig {
  apiBaseUrl: string;
}

@Injectable({
  providedIn: 'root',
})
export class RuntimeConfigService {
  private config: RuntimeConfig | null = null;

  /**
   * Loads runtime configuration from assets/config.json
   * This allows environment-specific config without rebuilding
   */
  async loadConfig(): Promise<void> {
    try {
      const response = await fetch('/assets/config.json');
      if (response.ok) {
        const config = await response.json();
        this.config = config;
      }
    } catch {
      // Config file not found or invalid - use environment defaults
      console.warn('Runtime config not found, using build-time defaults');
    }
  }

  /**
   * Get API base URL - prefers runtime config over build-time environment
   */
  get apiBaseUrl(): string {
    return this.config?.apiBaseUrl || environment.apiBaseUrl;
  }
}

/**
 * Factory function for APP_INITIALIZER
 */
export function initializeApp(configService: RuntimeConfigService): () => Promise<void> {
  return () => configService.loadConfig();
}
