import { describe, it, expect, vi } from 'vitest';
import { getEnabledFlags, isFeatureEnabled, fetchFeatureFlags, FeatureFlagData } from '../../shared/website/FeatureFlagHelpers';

describe('FeatureFlagHelpers', () => {
  const mockFeatureData: FeatureFlagData = {
    features: {
      'feature.a': 'enabled',
      'feature.b': 'disabled',
      'feature.c': 'coming_soon',
      'feature.d': 'enabled',
    },
    timestamp: '2026-01-17T16:00:00Z',
  };

  describe('getEnabledFlags()', () => {
    it('should return only enabled flags', () => {
      const enabled = getEnabledFlags(mockFeatureData);
      expect(enabled).toEqual(['feature.a', 'feature.d']);
    });

    it('should return empty array if no features', () => {
      expect(getEnabledFlags({ features: {}, timestamp: '' })).toEqual([]);
    });

    it('should handle null/undefined features', () => {
      expect(getEnabledFlags({ features: null as unknown as Record<string, string>, timestamp: '' })).toEqual([]);
    });
  });

  describe('isFeatureEnabled()', () => {
    it('should return true for enabled features', () => {
      expect(isFeatureEnabled(mockFeatureData, 'feature.a')).toBe(true);
      expect(isFeatureEnabled(mockFeatureData, 'feature.d')).toBe(true);
    });

    it('should return false for non-enabled features', () => {
      expect(isFeatureEnabled(mockFeatureData, 'feature.b')).toBe(false);
      expect(isFeatureEnabled(mockFeatureData, 'feature.c')).toBe(false);
      expect(isFeatureEnabled(mockFeatureData, 'non-existent')).toBe(false);
    });
  });

  describe('fetchFeatureFlags()', () => {
    it('should fetch and return feature flags', async () => {
      const mockFetcher = vi.fn().mockResolvedValue({
        ok: true,
        json: async () => mockFeatureData,
        status: 200,
      });

      const result = await fetchFeatureFlags(mockFetcher, 'http://api.test');
      
      expect(mockFetcher).toHaveBeenCalledWith('http://api.test/features');
      expect(result).toEqual(mockFeatureData);
    });

    it('should throw error if fetch fails', async () => {
      const mockFetcher = vi.fn().mockResolvedValue({
        ok: false,
        status: 500,
      });

      await expect(fetchFeatureFlags(mockFetcher, 'http://api.test')).rejects.toThrow('Failed to fetch feature flags: 500');
    });
  });
});
