/**
 * Zulip账号关联集成测试
 * 
 * 功能描述：
 * - 测试数据库和内存模式的切换
 * - 测试完整的业务流程
 * - 验证模块配置的正确性
 * 
 * @author angjustinl
 * @version 1.0.0
 * @since 2025-01-07
 */

import { Test, TestingModule } from '@nestjs/testing';
import { ConfigModule } from '@nestjs/config';
import { ZulipAccountsModule } from '../../src/core/db/zulip_accounts/zulip_accounts.module';
import { ZulipAccountsMemoryService } from '../../src/core/db/zulip_accounts/zulip_accounts_memory.service';
import { CreateZulipAccountDto } from '../../src/core/db/zulip_accounts/zulip_accounts.dto';

describe('ZulipAccountsModule Integration', () => {
  let memoryModule: TestingModule;

  beforeAll(async () => {
    // 测试内存模式
    memoryModule = await Test.createTestingModule({
      imports: [
        ConfigModule.forRoot({
          envFilePath: ['.env.test', '.env'],
          isGlobal: true,
        }),
        ZulipAccountsModule.forMemory()
      ],
    }).compile();
  });

  afterAll(async () => {
    if (memoryModule) {
      await memoryModule.close();
    }
  });

  describe('Memory Mode', () => {
    let service: ZulipAccountsMemoryService;

    beforeEach(() => {
      service = memoryModule.get<ZulipAccountsMemoryService>('ZulipAccountsService');
    });

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

    it('should create and retrieve account in memory', async () => {
      const createDto: CreateZulipAccountDto = {
        gameUserId: '77777',
        zulipUserId: 88888,
        zulipEmail: 'memory@example.com',
        zulipFullName: '内存测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      };

      // 创建账号关联
      const created = await service.create(createDto);
      expect(created).toBeDefined();
      expect(created.gameUserId).toBe('77777');
      expect(created.zulipEmail).toBe('memory@example.com');

      // 根据游戏用户ID查找
      const found = await service.findByGameUserId('77777');
      expect(found).toBeDefined();
      expect(found?.id).toBe(created.id);
    });

    it('should handle batch operations in memory', async () => {
      // 创建多个账号
      const accounts = [];
      for (let i = 1; i <= 3; i++) {
        const createDto: CreateZulipAccountDto = {
          gameUserId: `${20000 + i}`,
          zulipUserId: 30000 + i,
          zulipEmail: `batch${i}@example.com`,
          zulipFullName: `批量用户${i}`,
          zulipApiKeyEncrypted: 'encrypted_api_key',
          status: 'active',
        };
        const account = await service.create(createDto);
        accounts.push(account);
      }

      // 批量更新状态
      const ids = accounts.map(a => a.id);
      const batchResult = await service.batchUpdateStatus(ids, 'inactive');
      expect(batchResult.success).toBe(true);
      expect(batchResult.updatedCount).toBe(3);

      // 验证状态已更新
      for (const account of accounts) {
        const updated = await service.findById(account.id);
        expect(updated.status).toBe('inactive');
      }
    });

    it('should get statistics in memory', async () => {
      // 创建不同状态的账号
      const statuses: Array<'active' | 'inactive' | 'suspended' | 'error'> = ['active', 'inactive', 'suspended', 'error'];
      
      for (let i = 0; i < statuses.length; i++) {
        const createDto: CreateZulipAccountDto = {
          gameUserId: `${40000 + i}`,
          zulipUserId: 50000 + i,
          zulipEmail: `stats${i}@example.com`,
          zulipFullName: `统计用户${i}`,
          zulipApiKeyEncrypted: 'encrypted_api_key',
          status: statuses[i],
        };
        await service.create(createDto);
      }

      // 获取统计信息
      const stats = await service.getStatusStatistics();
      expect(stats.active).toBeGreaterThanOrEqual(1);
      expect(stats.inactive).toBeGreaterThanOrEqual(1);
      expect(stats.suspended).toBeGreaterThanOrEqual(1);
      expect(stats.error).toBeGreaterThanOrEqual(1);
      expect(stats.total).toBeGreaterThanOrEqual(4);
    });
  });

  describe('Cross-Mode Compatibility', () => {
    it('should have same interface for both modes', () => {
      const memoryService = memoryModule.get<ZulipAccountsMemoryService>('ZulipAccountsService');

      // 检查内存服务有所需的方法
      const methods = [
        'create',
        'findByGameUserId',
        'findByZulipUserId',
        'findByZulipEmail',
        'findById',
        'update',
        'updateByGameUserId',
        'delete',
        'deleteByGameUserId',
        'findMany',
        'findAccountsNeedingVerification',
        'findErrorAccounts',
        'batchUpdateStatus',
        'getStatusStatistics',
        'verifyAccount',
        'existsByEmail',
        'existsByZulipUserId',
      ];

      methods.forEach(method => {
        expect(typeof memoryService[method]).toBe('function');
      });
    });
  });
});