import { Test, TestingModule } from '@nestjs/testing';
import { ActiveRecallObservabilityService } from './active-recall-observability.service';

describe('ActiveRecallObservabilityService', () => {
  let service: ActiveRecallObservabilityService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [ActiveRecallObservabilityService],
    }).compile();

    service = module.get(ActiveRecallObservabilityService);
  });

  describe('计数器', () => {
    it('初始计数器全为 0', () => {
      const c = service.getCounters();
      expect(c.legacyRequests).toBe(0);
      expect(c.unifiedRequests).toBe(0);
      expect(c.unifiedCreateFailed).toBe(0);
      expect(c.unifiedExecuteSuccess).toBe(0);
      expect(c.unifiedExecuteFailed).toBe(0);
      expect(c.unifiedRetryCount).toBe(0);
      expect(c.projectorFailed).toBe(0);
      expect(c.rollbackCount).toBe(0);
    });

    it('Legacy 请求计数', () => {
      service.incrementLegacyRequests();
      service.incrementLegacyRequests();
      expect(service.getCounters().legacyRequests).toBe(2);
    });

    it('Unified 请求计数', () => {
      service.incrementUnifiedRequests();
      expect(service.getCounters().unifiedRequests).toBe(1);
    });

    it('Unified 创建失败计数', () => {
      service.incrementUnifiedCreateFailed();
      service.incrementUnifiedCreateFailed();
      expect(service.getCounters().unifiedCreateFailed).toBe(2);
    });

    it('Unified 执行成功计数 + 平均耗时', () => {
      service.incrementUnifiedExecuteSuccess(100);
      service.incrementUnifiedExecuteSuccess(300);
      const c = service.getCounters();
      expect(c.unifiedExecuteSuccess).toBe(2);
      expect(c.unifiedAvgDurationMs).toBe(200);
    });

    it('Unified 执行失败计数', () => {
      service.incrementUnifiedExecuteFailed();
      expect(service.getCounters().unifiedExecuteFailed).toBe(1);
    });

    it('retry / projector / rollback 计数', () => {
      service.incrementUnifiedRetry();
      service.incrementProjectorFailed();
      service.incrementRollback();
      const c = service.getCounters();
      expect(c.unifiedRetryCount).toBe(1);
      expect(c.projectorFailed).toBe(1);
      expect(c.rollbackCount).toBe(1);
    });

    it('resetCounters 归零', () => {
      service.incrementLegacyRequests();
      service.incrementUnifiedRequests();
      service.resetCounters();
      const c = service.getCounters();
      expect(c.legacyRequests).toBe(0);
      expect(c.unifiedRequests).toBe(0);
    });
  });

  describe('结构化日志', () => {
    it('logRequest 不抛异常', () => {
      expect(() =>
        service.logRequest({
          requestId: 'req-1',
          activeRecallId: 'q-1',
          userId: 'u-1',
          engineMode: 'unified',
          jobType: 'active_recall',
          queueName: 'ai-interactive',
        }),
      ).not.toThrow();
    });

    it('logJobCreated 不抛异常', () => {
      expect(() =>
        service.logJobCreated({
          requestId: 'req-1',
          jobId: 'job-1',
          activeRecallId: 'q-1',
          userId: 'u-1',
          engineMode: 'unified',
          jobType: 'active_recall',
          queueName: 'ai-interactive',
        }),
      ).not.toThrow();
    });

    it('logJobCreateFailed 不记录用户完整答案', () => {
      // 日志仅记录 error message，不记录 answerText
      expect(() =>
        service.logJobCreateFailed(
          {
            requestId: 'req-1',
            activeRecallId: 'q-1',
            userId: 'u-1',
            engineMode: 'unified',
            jobType: 'active_recall',
            queueName: 'ai-interactive',
          },
          'DB error',
        ),
      ).not.toThrow();
    });

    it('logExecutionCompleted 包含完整链路字段', () => {
      expect(() =>
        service.logExecutionCompleted({
          requestId: 'req-1',
          jobId: 'job-1',
          activeRecallId: 'q-1',
          userId: 'u-1',
          engineMode: 'unified',
          jobType: 'active_recall',
          queueName: 'ai-interactive',
          durationMs: 1234,
          lifecycleStatus: 'succeeded',
          attemptCount: 1,
        }),
      ).not.toThrow();
    });

    it('logRollback 不抛异常', () => {
      expect(() =>
        service.logRollback('u-1', 'Feature flag switched to legacy'),
      ).not.toThrow();
    });
  });
});
