import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ConfigLoadResult, FlattenedFeatures } from '../config/feature-types';
import { FeaturesController } from './features.controller';

// Mock the feature-loader module
vi.mock('../config/feature-loader', () => ({
  loadFeatureConfig: vi.fn(),
}));

import { loadFeatureConfig } from '../config/feature-loader';

describe('FeaturesController', () => {
  let controller: FeaturesController;

  beforeEach(() => {
    controller = new FeaturesController();
    vi.clearAllMocks();
  });

  it('should be defined', () => {
    expect(controller).toBeDefined();
  });

  it('should return features with correct shape', async () => {
    const mockFeatures: FlattenedFeatures = {
      'platform.dashboard': 'enabled',
      'platform.leagues': 'enabled',
      'sponsors.portal': 'enabled',
    };

    const mockResult: ConfigLoadResult = {
      features: mockFeatures,
      loadedFrom: 'config-file',
      configPath: 'apps/api/src/config/features.config.ts',
    };

    vi.mocked(loadFeatureConfig).mockResolvedValue(mockResult);

    const result = await controller.getFeatures();

    expect(loadFeatureConfig).toHaveBeenCalledTimes(1);
    expect(result).toHaveProperty('features');
    expect(result).toHaveProperty('loadedFrom');
    expect(result).toHaveProperty('timestamp');
    expect(result.features).toEqual(mockFeatures);
    expect(result.loadedFrom).toBe('config-file');
    expect(result.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);
  });

  it('should handle empty features', async () => {
    const mockResult: ConfigLoadResult = {
      features: {},
      loadedFrom: 'defaults',
    };

    vi.mocked(loadFeatureConfig).mockResolvedValue(mockResult);

    const result = await controller.getFeatures();

    expect(result.features).toEqual({});
    expect(result.loadedFrom).toBe('defaults');
    expect(typeof result.timestamp).toBe('string');
  });

  it('should include timestamp as ISO string', async () => {
    const mockResult: ConfigLoadResult = {
      features: { 'test.feature': 'enabled' as const },
      loadedFrom: 'config-file',
    };

    vi.mocked(loadFeatureConfig).mockResolvedValue(mockResult);

    const result = await controller.getFeatures();
    const timestamp = new Date(result.timestamp);

    expect(timestamp instanceof Date).toBe(true);
    expect(timestamp.toISOString()).toBe(result.timestamp);
  });
});