import { useSettingsStore } from '@/store/use-settings';
import type { ProviderProfile, ProviderSettings, ConnectionValidationResult } from '@/types/settings';

/**
 * Provider Management Service - Business logic for multi-provider management
 * Following Logic Sandwich pattern: UI -> Store -> Service
 */
export class ProviderManagementService {
  /**
   * Get the currently active provider profile
   * @returns Active provider profile or null if none set
   */
  static getActiveProvider(): ProviderProfile | null {
    const state = useSettingsStore.getState();
    const { activeProviderId, savedProviders } = state;

    if (!activeProviderId) return null;

    return savedProviders.find(p => p.id === activeProviderId) || null;
  }

  /**
   * Get all saved provider profiles
   * @returns Array of all saved profiles
   */
  static getAllProviders(): ProviderProfile[] {
    return useSettingsStore.getState().savedProviders;
  }

  /**
   * Add a new provider profile
   * @param profile - Provider profile data (id generated automatically)
   * @returns The ID of the newly created profile
   * @throws Error if validation fails
   */
  static addProviderProfile(
    profile: Omit<ProviderProfile, 'id' | 'createdAt' | 'updatedAt'>
  ): string {
    // Basic schema validation
    if (!profile.name?.trim()) throw new Error('Provider name is required');
    if (!profile.baseUrl?.trim()) throw new Error('Base URL is required');
    if (!profile.apiKey?.trim()) throw new Error('API Key is required');
    if (!profile.modelName?.trim()) throw new Error('Model Name is required');

    const actions = useSettingsStore.getState().actions;
    return actions.addProvider(profile);
  }

  /**
   * Remove a provider profile
   * @param id - ID of the provider to remove
   */
  static removeProviderProfile(id: string): void {
    const actions = useSettingsStore.getState().actions;
    actions.removeProvider(id);
    // Store handles auto-selection of next provider
  }

  /**
   * Set a provider as the active one
   * @param id - ID of the provider to activate
   */
  static setActiveProvider(id: string): void {
    const actions = useSettingsStore.getState().actions;
    actions.setActiveProvider(id);
  }

  /**
   * Update an existing provider profile
   * @param id - ID of the provider to update
   * @param updates - Partial profile data to update
   */
  static updateProviderProfile(
    id: string,
    updates: Partial<Omit<ProviderProfile, 'id' | 'createdAt'>>
  ): void {
    const actions = useSettingsStore.getState().actions;
    actions.updateProvider(id, updates);
  }

  /**
   * Get provider settings compatible with legacy ProviderSettings interface
   * Used by LLMService and ChatService for backward compatibility
   * @returns Provider settings for the active provider or defaults
   */
  static getActiveProviderSettings(): ProviderSettings {
    const active = this.getActiveProvider();

    if (active) {
      return {
        apiKey: active.apiKey,
        baseUrl: active.baseUrl,
        modelName: active.modelName,
      };
    }

    // Return empty defaults if no active provider
    return {
      apiKey: '',
      baseUrl: 'https://api.openai.com/v1',
      modelName: 'gpt-4o',
    };
  }

  /**
   * Check if any provider is configured
   * @returns true if at least one provider profile exists
   */
  static hasAnyProvider(): boolean {
    return useSettingsStore.getState().savedProviders.length > 0;
  }

  /**
   * Validate connection to LLM provider
   * @param baseUrl - The API base URL
   * @param apiKey - The API key for authentication
   * @param modelName - The model name to test
   * @returns Promise resolving to ConnectionValidationResult
   */
  static async validateConnection(
    baseUrl: string,
    apiKey: string,
    modelName: string
  ): Promise<ConnectionValidationResult> {
    const { LLMService } = await import('./llm-service');
    return LLMService.validateConnection(baseUrl, apiKey, modelName);
  }
}
