import { CoreEngineService } from './CoreEngineService';
import { RuleEngineService } from './RuleEngineService';
import { WorkflowEngineService } from './WorkflowEngineService';
import { RedisService } from '../cache/RedisService';

describe('CoreEngineService', () => {
  let coreEngineService: CoreEngineService;
  let ruleEngineService: RuleEngineService;
  let workflowEngineService: WorkflowEngineService;
  let redisService: RedisService;

  beforeEach(() => {
    ruleEngineService = new RuleEngineService();
    workflowEngineService = new WorkflowEngineService();
    redisService = new RedisService();
    coreEngineService = new CoreEngineService(ruleEngineService, workflowEngineService, redisService);
  });

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

  it('should process business request', async () => {
    const request = { id: '123', type: 'test' };
    const context = { userId: 'user123', timestamp: new Date().toISOString() };

    const result = await coreEngineService.processBusinessRequest(request, context);

    expect(result).toBeDefined();
    expect(result.validated).toBe(true);
    expect(result.processed).toBe(true);
    expect(result.responded).toBe(true);
    expect(result.result).toBe('success');
  });

  it('should register business rule', async () => {
    const rule = {
      condition: (data: any) => data.id === '123',
      action: (data: any) => ({ ...data, approved: true })
    };

    const ruleId = await coreEngineService.registerBusinessRule(rule);

    expect(ruleId).toBeDefined();
    expect(typeof ruleId).toBe('string');
  });

  it('should register workflow', async () => {
    const workflow = {
      name: 'Test Workflow',
      steps: [
        {
          id: 'step1',
          name: 'Test Step 1',
          action: (data: any) => ({ ...data, step1: true })
        }
      ]
    };

    const workflowId = await coreEngineService.registerWorkflow(workflow);

    expect(workflowId).toBeDefined();
    expect(typeof workflowId).toBe('string');
  });

  it('should get system status', async () => {
    const status = await coreEngineService.getSystemStatus();

    expect(status).toBeDefined();
    expect(status.status).toBe('healthy');
    expect(status.services).toBeDefined();
    expect(status.services.ruleEngine).toBeDefined();
    expect(status.services.workflowEngine).toBeDefined();
    expect(status.services.redis).toBeDefined();
  });

  it('should use cached result when available', async () => {
    const request = { id: '456', type: 'cached' };
    const context = { userId: 'user456', timestamp: new Date().toISOString() };

    // First request (should not be cached)
    const firstResult = await coreEngineService.processBusinessRequest(request, context);
    
    // Second request (should be cached)
    const secondResult = await coreEngineService.processBusinessRequest(request, context);

    expect(firstResult).toEqual(secondResult);
  });
});
