/**
 * ML Service Tests
 */

import { describe, it, expect, vi, beforeEach } from 'vitest';

// Mock fetch globally
const mockFetch = vi.fn();
vi.stubGlobal('fetch', mockFetch);

describe('ML Service', () => {
  beforeEach(() => {
    mockFetch.mockClear();
  });

  describe('getICTAnalysis', () => {
    it('should fetch ICT analysis for a symbol', async () => {
      const mockAnalysis = {
        symbol: 'EURUSD',
        timeframe: '1H',
        market_bias: 'bullish',
        bias_confidence: 0.75,
        score: 72,
        order_blocks: [],
        fair_value_gaps: [],
        signals: ['bullish_ob_fresh'],
      };

      mockFetch.mockResolvedValueOnce({
        ok: true,
        json: async () => mockAnalysis,
      });

      // Dynamic import to get mocked version
      const { getICTAnalysis } = await import('../services/mlService');
      const result = await getICTAnalysis('EURUSD', '1H');

      expect(mockFetch).toHaveBeenCalledWith(
        expect.stringContaining('/api/ict/EURUSD'),
        expect.objectContaining({ method: 'POST' })
      );
      expect(result).toEqual(mockAnalysis);
    });

    it('should return null on 404', async () => {
      mockFetch.mockResolvedValueOnce({
        ok: false,
        status: 404,
      });

      const { getICTAnalysis } = await import('../services/mlService');
      const result = await getICTAnalysis('INVALID');
      expect(result).toBeNull();
    });

    it('should return null on error', async () => {
      mockFetch.mockRejectedValueOnce(new Error('Network error'));

      const { getICTAnalysis } = await import('../services/mlService');
      const result = await getICTAnalysis('EURUSD');
      expect(result).toBeNull();
    });
  });

  describe('checkHealth', () => {
    it('should return true when healthy', async () => {
      mockFetch.mockResolvedValueOnce({ ok: true });

      const { checkHealth } = await import('../services/mlService');
      const result = await checkHealth();
      expect(result).toBe(true);
    });

    it('should return false when unhealthy', async () => {
      mockFetch.mockResolvedValueOnce({ ok: false });

      const { checkHealth } = await import('../services/mlService');
      const result = await checkHealth();
      expect(result).toBe(false);
    });

    it('should return false on error', async () => {
      mockFetch.mockRejectedValueOnce(new Error('Network error'));

      const { checkHealth } = await import('../services/mlService');
      const result = await checkHealth();
      expect(result).toBe(false);
    });
  });
});
