/**
 * Tests for LLMService Provider Integration
 * Story 4.4: Provider Switching
 */

import { describe, it, expect, beforeEach, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { LLMService } from './llm-service';
import { ProviderManagementService } from './provider-management-service';
import { useSettingsStore } from '@/store/use-settings';
import type { ConnectionValidationResult } from '@/types/settings';

// Mock fetch for testing
global.fetch = vi.fn();

describe('LLMService Provider Integration', () => {
  beforeEach(() => {
    // Reset store state before each test
    useSettingsStore.getState().actions.clearSettings();
    useSettingsStore.setState({
      providerMigrationState: {
        hasMigrated: false,
      },
      savedProviders: [],
      activeProviderId: null,
    });

    // Clear fetch mocks
    vi.mocked(fetch).mockClear();
  });

  describe('validateConnection integration', () => {
    it('should use active provider settings for validation', async () => {
      // Setup mock response
      vi.mocked(fetch).mockResolvedValueOnce({
        ok: true,
        json: async () => ({}),
      } as Response);

      // Add a provider
      ProviderManagementService.addProviderProfile({
        name: 'Test Provider',
        baseUrl: 'https://api.test.com/v1',
        apiKey: 'sk-test-key',
        modelName: 'test-model',
      });

      // Validate connection (should use active provider)
      const result: ConnectionValidationResult = await LLMService.validateConnection(
        'https://api.test.com/v1', // This param is now ignored, using active provider instead
        'sk-test-key', // This param is now ignored
        'test-model' // This param is now ignored
      );

      // Verify the call was made with correct parameters
      expect(vi.mocked(fetch)).toHaveBeenCalledWith(
        'https://api.test.com/v1/chat/completions',
        expect.objectContaining({
          method: 'POST',
          headers: expect.objectContaining({
            'Authorization': 'Bearer sk-test-key',
          }),
        })
      );

      // For now, validateConnection still uses direct params (we'll update it next)
      expect(result.isValid).toBe(true);
    });
  });

  describe('getActiveProviderSettings integration', () => {
    it('should return empty defaults when no providers configured', () => {
      const settings = ProviderManagementService.getActiveProviderSettings();

      expect(settings.apiKey).toBe('');
      expect(settings.baseUrl).toBe('https://api.openai.com/v1');
      expect(settings.modelName).toBe('gpt-4o');
    });

    it('should return active provider settings', () => {
      ProviderManagementService.addProviderProfile({
        name: 'Active Provider',
        baseUrl: 'https://api.active.com/v1',
        apiKey: 'sk-active-key',
        modelName: 'active-model',
      });

      const settings = ProviderManagementService.getActiveProviderSettings();

      expect(settings.apiKey).toBe('sk-active-key');
      expect(settings.baseUrl).toBe('https://api.active.com/v1');
      expect(settings.modelName).toBe('active-model');
    });

    it('should update settings when switching active provider', () => {
      const id1 = ProviderManagementService.addProviderProfile({
        name: 'Provider 1',
        baseUrl: 'https://api.p1.com/v1',
        apiKey: 'sk-p1',
        modelName: 'model1',
      });

      const id2 = ProviderManagementService.addProviderProfile({
        name: 'Provider 2',
        baseUrl: 'https://api.p2.com/v1',
        apiKey: 'sk-p2',
        modelName: 'model2',
      });

      // Provider 1 should be active (first provider auto-selected)
      let settings = ProviderManagementService.getActiveProviderSettings();
      expect(settings.modelName).toBe('model1');

      // Switch to Provider 2
      ProviderManagementService.setActiveProvider(id2);

      settings = ProviderManagementService.getActiveProviderSettings();
      expect(settings.modelName).toBe('model2');
      expect(settings.apiKey).toBe('sk-p2');
    });
  });
});
