/**
 * Zulip账号关联内存数据访问层测试
 * 
 * 功能描述：
 * - 测试内存Repository层的数据访问逻辑
 * - 验证内存存储的CRUD操作
 * - 测试数据一致性和并发安全
 * - 测试与数据库Repository的接口一致性
 * - 确保内存存储的正确性和性能
 * 
 * 最近修改：
 * - 2026-01-12: 代码规范优化 - 优化测试用例，修复时间断言和限制逻辑测试 (修改者: moyin)
 * - 2026-01-12: 代码规范优化 - 创建缺失的测试文件，确保测试覆盖完整性 (修改者: moyin)
 * 
 * @author moyin
 * @version 1.0.1
 * @since 2026-01-12
 * @lastModified 2026-01-12
 */

import { Test, TestingModule } from '@nestjs/testing';
import { ZulipAccountsMemoryRepository } from './zulip_accounts_memory.repository';
import { ZulipAccounts } from './zulip_accounts.entity';
import {
  CreateZulipAccountData,
  UpdateZulipAccountData,
  ZulipAccountQueryOptions,
} from './zulip_accounts.types';

describe('ZulipAccountsMemoryRepository', () => {
  let repository: ZulipAccountsMemoryRepository;

  const mockAccount: ZulipAccounts = {
    id: BigInt(1),
    gameUserId: BigInt(12345),
    zulipUserId: 67890,
    zulipEmail: 'test@example.com',
    zulipFullName: '测试用户',
    zulipApiKeyEncrypted: 'encrypted_api_key',
    status: 'active',
    lastVerifiedAt: new Date('2026-01-12T10:00:00Z'),
    lastSyncedAt: new Date('2026-01-12T10:00:00Z'),
    errorMessage: null,
    retryCount: 0,
    createdAt: new Date('2026-01-12T09:00:00Z'),
    updatedAt: new Date('2026-01-12T10:00:00Z'),
    gameUser: null,
    isActive: () => true,
    isHealthy: () => true,
    canBeDeleted: () => false,
    isStale: () => false,
    needsVerification: () => false,
    shouldRetry: () => false,
    updateVerificationTime: () => {},
    updateSyncTime: () => {},
    setError: () => {},
    clearError: () => {},
    resetRetryCount: () => {},
    activate: () => {},
    suspend: () => {},
    deactivate: () => {},
  };

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

    repository = module.get<ZulipAccountsMemoryRepository>(ZulipAccountsMemoryRepository);
  });

  afterEach(() => {
    // 清理内存数据
    (repository as any).accounts.clear();
    (repository as any).nextId = BigInt(1);
  });

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

  describe('create', () => {
    const createDto: CreateZulipAccountData = {
      gameUserId: BigInt(12345),
      zulipUserId: 67890,
      zulipEmail: 'test@example.com',
      zulipFullName: '测试用户',
      zulipApiKeyEncrypted: 'encrypted_api_key',
      status: 'active',
    };

    it('should create account successfully', async () => {
      const result = await repository.create(createDto);

      expect(result).toBeDefined();
      expect(result.gameUserId).toBe(BigInt(12345));
      expect(result.zulipUserId).toBe(67890);
      expect(result.zulipEmail).toBe('test@example.com');
      expect(result.zulipFullName).toBe('测试用户');
      expect(result.status).toBe('active');
      expect(result.id).toBe(BigInt(1));
      expect(result.createdAt).toBeInstanceOf(Date);
      expect(result.updatedAt).toBeInstanceOf(Date);
    });

    it('should throw error if game user already exists', async () => {
      // 先创建一个账号
      await repository.create(createDto);

      // 尝试创建重复的游戏用户ID
      await expect(repository.create(createDto)).rejects.toThrow(
        'Game user 12345 already has a Zulip account'
      );
    });

    it('should throw error if zulip user already exists', async () => {
      // 先创建一个账号
      await repository.create(createDto);

      // 尝试创建不同游戏用户但相同Zulip用户的账号
      const duplicateZulipUser = {
        ...createDto,
        gameUserId: BigInt(54321),
      };

      await expect(repository.create(duplicateZulipUser)).rejects.toThrow(
        'Zulip user 67890 is already linked'
      );
    });

    it('should throw error if email already exists', async () => {
      // 先创建一个账号
      await repository.create(createDto);

      // 尝试创建不同用户但相同邮箱的账号
      const duplicateEmail = {
        ...createDto,
        gameUserId: BigInt(54321),
        zulipUserId: 98765,
      };

      await expect(repository.create(duplicateEmail)).rejects.toThrow(
        'Zulip email test@example.com is already linked'
      );
    });

    it('should auto-increment ID for multiple accounts', async () => {
      const account1 = await repository.create(createDto);
      
      const createDto2 = {
        ...createDto,
        gameUserId: BigInt(54321),
        zulipUserId: 98765,
        zulipEmail: 'test2@example.com',
      };
      const account2 = await repository.create(createDto2);

      expect(account1.id).toBe(BigInt(1));
      expect(account2.id).toBe(BigInt(2));
    });
  });

  describe('findByGameUserId', () => {
    beforeEach(async () => {
      await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test@example.com',
        zulipFullName: '测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      });
    });

    it('should find account by game user ID', async () => {
      const result = await repository.findByGameUserId(BigInt(12345));

      expect(result).toBeDefined();
      expect(result?.gameUserId).toBe(BigInt(12345));
      expect(result?.zulipEmail).toBe('test@example.com');
    });

    it('should return null if not found', async () => {
      const result = await repository.findByGameUserId(BigInt(99999));

      expect(result).toBeNull();
    });

    it('should handle includeGameUser parameter (ignored in memory mode)', async () => {
      const result = await repository.findByGameUserId(BigInt(12345), true);

      expect(result).toBeDefined();
      expect(result?.gameUserId).toBe(BigInt(12345));
    });
  });

  describe('findByZulipUserId', () => {
    beforeEach(async () => {
      await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test@example.com',
        zulipFullName: '测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      });
    });

    it('should find account by zulip user ID', async () => {
      const result = await repository.findByZulipUserId(67890);

      expect(result).toBeDefined();
      expect(result?.zulipUserId).toBe(67890);
      expect(result?.gameUserId).toBe(BigInt(12345));
    });

    it('should return null if not found', async () => {
      const result = await repository.findByZulipUserId(99999);

      expect(result).toBeNull();
    });
  });

  describe('findByZulipEmail', () => {
    beforeEach(async () => {
      await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test@example.com',
        zulipFullName: '测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      });
    });

    it('should find account by zulip email', async () => {
      const result = await repository.findByZulipEmail('test@example.com');

      expect(result).toBeDefined();
      expect(result?.zulipEmail).toBe('test@example.com');
      expect(result?.gameUserId).toBe(BigInt(12345));
    });

    it('should return null if not found', async () => {
      const result = await repository.findByZulipEmail('notfound@example.com');

      expect(result).toBeNull();
    });
  });

  describe('findById', () => {
    let createdAccount: ZulipAccounts;

    beforeEach(async () => {
      createdAccount = await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test@example.com',
        zulipFullName: '测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      });
    });

    it('should find account by ID', async () => {
      const result = await repository.findById(createdAccount.id);

      expect(result).toBeDefined();
      expect(result?.id).toBe(createdAccount.id);
      expect(result?.gameUserId).toBe(BigInt(12345));
    });

    it('should return null if not found', async () => {
      const result = await repository.findById(BigInt(99999));

      expect(result).toBeNull();
    });
  });

  describe('update', () => {
    let createdAccount: ZulipAccounts;

    beforeEach(async () => {
      createdAccount = await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test@example.com',
        zulipFullName: '测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      });
    });

    it('should update account successfully', async () => {
      const updateDto: UpdateZulipAccountData = {
        zulipFullName: '更新的用户名',
        status: 'inactive',
      };

      // 记录更新前的时间
      const beforeUpdate = createdAccount.updatedAt.getTime();
      
      // 等待一小段时间确保时间戳不同
      await new Promise(resolve => setTimeout(resolve, 1));

      const result = await repository.update(createdAccount.id, updateDto);

      expect(result).toBeDefined();
      expect(result?.zulipFullName).toBe('更新的用户名');
      expect(result?.status).toBe('inactive');
      expect(result?.updatedAt.getTime()).toBeGreaterThan(beforeUpdate);
    });

    it('should return null if account not found', async () => {
      const updateDto: UpdateZulipAccountData = {
        status: 'inactive',
      };

      const result = await repository.update(BigInt(99999), updateDto);

      expect(result).toBeNull();
    });

    it('should update only specified fields', async () => {
      const updateDto: UpdateZulipAccountData = {
        status: 'suspended',
      };

      const result = await repository.update(createdAccount.id, updateDto);

      expect(result).toBeDefined();
      expect(result?.status).toBe('suspended');
      expect(result?.zulipFullName).toBe('测试用户'); // 未更新的字段保持不变
    });
  });

  describe('updateByGameUserId', () => {
    beforeEach(async () => {
      await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test@example.com',
        zulipFullName: '测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      });
    });

    it('should update account by game user ID', async () => {
      const updateDto: UpdateZulipAccountData = {
        status: 'suspended',
        errorMessage: '账号被暂停',
      };

      const result = await repository.updateByGameUserId(BigInt(12345), updateDto);

      expect(result).toBeDefined();
      expect(result?.status).toBe('suspended');
      expect(result?.errorMessage).toBe('账号被暂停');
    });

    it('should return null if account not found', async () => {
      const updateDto: UpdateZulipAccountData = {
        status: 'inactive',
      };

      const result = await repository.updateByGameUserId(BigInt(99999), updateDto);

      expect(result).toBeNull();
    });
  });

  describe('delete', () => {
    let createdAccount: ZulipAccounts;

    beforeEach(async () => {
      createdAccount = await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test@example.com',
        zulipFullName: '测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      });
    });

    it('should delete account successfully', async () => {
      const result = await repository.delete(createdAccount.id);

      expect(result).toBe(true);

      // 验证账号已被删除
      const found = await repository.findById(createdAccount.id);
      expect(found).toBeNull();
    });

    it('should return false if account not found', async () => {
      const result = await repository.delete(BigInt(99999));

      expect(result).toBe(false);
    });
  });

  describe('deleteByGameUserId', () => {
    beforeEach(async () => {
      await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test@example.com',
        zulipFullName: '测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      });
    });

    it('should delete account by game user ID', async () => {
      const result = await repository.deleteByGameUserId(BigInt(12345));

      expect(result).toBe(true);

      // 验证账号已被删除
      const found = await repository.findByGameUserId(BigInt(12345));
      expect(found).toBeNull();
    });

    it('should return false if account not found', async () => {
      const result = await repository.deleteByGameUserId(BigInt(99999));

      expect(result).toBe(false);
    });
  });

  describe('findMany', () => {
    beforeEach(async () => {
      // 创建多个测试账号
      await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test1@example.com',
        zulipFullName: '测试用户1',
        zulipApiKeyEncrypted: 'encrypted_api_key_1',
        status: 'active',
      });

      await repository.create({
        gameUserId: BigInt(54321),
        zulipUserId: 98765,
        zulipEmail: 'test2@example.com',
        zulipFullName: '测试用户2',
        zulipApiKeyEncrypted: 'encrypted_api_key_2',
        status: 'inactive',
      });

      await repository.create({
        gameUserId: BigInt(11111),
        zulipUserId: 22222,
        zulipEmail: 'test3@example.com',
        zulipFullName: '测试用户3',
        zulipApiKeyEncrypted: 'encrypted_api_key_3',
        status: 'active',
      });
    });

    it('should find all accounts without filters', async () => {
      const result = await repository.findMany({});

      expect(result).toHaveLength(3);
    });

    it('should filter by game user ID', async () => {
      const options: ZulipAccountQueryOptions = {
        gameUserId: BigInt(12345),
      };

      const result = await repository.findMany(options);

      expect(result).toHaveLength(1);
      expect(result[0].gameUserId).toBe(BigInt(12345));
    });

    it('should filter by zulip user ID', async () => {
      const options: ZulipAccountQueryOptions = {
        zulipUserId: 67890,
      };

      const result = await repository.findMany(options);

      expect(result).toHaveLength(1);
      expect(result[0].zulipUserId).toBe(67890);
    });

    it('should filter by email', async () => {
      const options: ZulipAccountQueryOptions = {
        zulipEmail: 'test2@example.com',
      };

      const result = await repository.findMany(options);

      expect(result).toHaveLength(1);
      expect(result[0].zulipEmail).toBe('test2@example.com');
    });

    it('should filter by status', async () => {
      const options: ZulipAccountQueryOptions = {
        status: 'active',
      };

      const result = await repository.findMany(options);

      expect(result).toHaveLength(2);
      result.forEach(account => {
        expect(account.status).toBe('active');
      });
    });

    it('should combine multiple filters', async () => {
      const options: ZulipAccountQueryOptions = {
        status: 'active',
        gameUserId: BigInt(12345),
      };

      const result = await repository.findMany(options);

      expect(result).toHaveLength(1);
      expect(result[0].gameUserId).toBe(BigInt(12345));
      expect(result[0].status).toBe('active');
    });
  });

  describe('findAccountsNeedingVerification', () => {
    beforeEach(async () => {
      const now = new Date();
      const oldDate = new Date(now.getTime() - 25 * 60 * 60 * 1000); // 25小时前

      // 创建需要验证的账号（从未验证）
      await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'never_verified@example.com',
        zulipFullName: '从未验证用户',
        zulipApiKeyEncrypted: 'encrypted_api_key_1',
        status: 'active',
      });

      // 创建需要验证的账号（验证过期）
      const expiredAccount = await repository.create({
        gameUserId: BigInt(54321),
        zulipUserId: 98765,
        zulipEmail: 'expired@example.com',
        zulipFullName: '验证过期用户',
        zulipApiKeyEncrypted: 'encrypted_api_key_2',
        status: 'active',
      });
      // 手动设置过期的验证时间
      (repository as any).accounts.set(expiredAccount.id, {
        ...expiredAccount,
        lastVerifiedAt: oldDate,
      });

      // 创建不需要验证的账号（最近验证过）
      const recentAccount = await repository.create({
        gameUserId: BigInt(11111),
        zulipUserId: 22222,
        zulipEmail: 'recent@example.com',
        zulipFullName: '最近验证用户',
        zulipApiKeyEncrypted: 'encrypted_api_key_3',
        status: 'active',
      });
      // 手动设置最近的验证时间
      (repository as any).accounts.set(recentAccount.id, {
        ...recentAccount,
        lastVerifiedAt: now,
      });

      // 创建非活跃账号（不应包含在结果中）
      await repository.create({
        gameUserId: BigInt(99999),
        zulipUserId: 88888,
        zulipEmail: 'inactive@example.com',
        zulipFullName: '非活跃用户',
        zulipApiKeyEncrypted: 'encrypted_api_key_4',
        status: 'inactive',
      });
    });

    it('should find accounts needing verification', async () => {
      const maxAge = 24 * 60 * 60 * 1000; // 24小时
      const result = await repository.findAccountsNeedingVerification(maxAge);

      expect(result).toHaveLength(2);
      
      const emails = result.map(account => account.zulipEmail);
      expect(emails).toContain('never_verified@example.com');
      expect(emails).toContain('expired@example.com');
      expect(emails).not.toContain('recent@example.com');
      expect(emails).not.toContain('inactive@example.com');
    });

    it('should respect the limit', async () => {
      // 创建更多需要验证的账号
      for (let i = 0; i < 150; i++) {
        await repository.create({
          gameUserId: BigInt(100000 + i),
          zulipUserId: 100000 + i,
          zulipEmail: `bulk${i}@example.com`,
          zulipFullName: `批量用户${i}`,
          zulipApiKeyEncrypted: `encrypted_api_key_${i}`,
          status: 'active',
        });
      }

      const result = await repository.findAccountsNeedingVerification();

      // 检查是否应用了默认限制（从常量文件获取实际限制值）
      const expectedLimit = 100; // DEFAULT_VERIFICATION_QUERY_LIMIT 的值
      expect(result.length).toBeLessThanOrEqual(expectedLimit);
      
      // 验证返回的都是需要验证的账号
      result.forEach(account => {
        expect(account.status).toBe('active');
        expect(account.lastVerifiedAt).toBeNull();
      });
    });
  });

  describe('findErrorAccounts', () => {
    beforeEach(async () => {
      // 创建可重试的错误账号
      const errorAccount1 = await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'error1@example.com',
        zulipFullName: '错误用户1',
        zulipApiKeyEncrypted: 'encrypted_api_key_1',
        status: 'error',
      });
      // 手动设置重试次数
      (repository as any).accounts.set(errorAccount1.id, {
        ...errorAccount1,
        retryCount: 1,
      });

      // 创建达到最大重试次数的错误账号
      const errorAccount2 = await repository.create({
        gameUserId: BigInt(54321),
        zulipUserId: 98765,
        zulipEmail: 'error2@example.com',
        zulipFullName: '错误用户2',
        zulipApiKeyEncrypted: 'encrypted_api_key_2',
        status: 'error',
      });
      // 手动设置重试次数
      (repository as any).accounts.set(errorAccount2.id, {
        ...errorAccount2,
        retryCount: 5,
      });

      // 创建正常状态的账号
      await repository.create({
        gameUserId: BigInt(11111),
        zulipUserId: 22222,
        zulipEmail: 'normal@example.com',
        zulipFullName: '正常用户',
        zulipApiKeyEncrypted: 'encrypted_api_key_3',
        status: 'active',
      });
    });

    it('should find error accounts that can be retried', async () => {
      const result = await repository.findErrorAccounts(3);

      expect(result).toHaveLength(1);
      expect(result[0].zulipEmail).toBe('error1@example.com');
      expect(result[0].retryCount).toBe(1);
    });

    it('should exclude accounts that exceeded max retry count', async () => {
      const result = await repository.findErrorAccounts(3);

      const emails = result.map(account => account.zulipEmail);
      expect(emails).not.toContain('error2@example.com');
    });

    it('should exclude non-error accounts', async () => {
      const result = await repository.findErrorAccounts(3);

      const emails = result.map(account => account.zulipEmail);
      expect(emails).not.toContain('normal@example.com');
    });
  });

  describe('batchUpdateStatus', () => {
    let account1: ZulipAccounts;
    let account2: ZulipAccounts;
    let account3: ZulipAccounts;

    beforeEach(async () => {
      account1 = await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test1@example.com',
        zulipFullName: '测试用户1',
        zulipApiKeyEncrypted: 'encrypted_api_key_1',
        status: 'active',
      });

      account2 = await repository.create({
        gameUserId: BigInt(54321),
        zulipUserId: 98765,
        zulipEmail: 'test2@example.com',
        zulipFullName: '测试用户2',
        zulipApiKeyEncrypted: 'encrypted_api_key_2',
        status: 'active',
      });

      account3 = await repository.create({
        gameUserId: BigInt(11111),
        zulipUserId: 22222,
        zulipEmail: 'test3@example.com',
        zulipFullName: '测试用户3',
        zulipApiKeyEncrypted: 'encrypted_api_key_3',
        status: 'active',
      });
    });

    it('should batch update status for existing accounts', async () => {
      const ids = [account1.id, account2.id];
      const result = await repository.batchUpdateStatus(ids, 'suspended');

      expect(result).toBe(2);

      // 验证状态已更新
      const updated1 = await repository.findById(account1.id);
      const updated2 = await repository.findById(account2.id);
      const unchanged = await repository.findById(account3.id);

      expect(updated1?.status).toBe('suspended');
      expect(updated2?.status).toBe('suspended');
      expect(unchanged?.status).toBe('active');
    });

    it('should return 0 for non-existent accounts', async () => {
      const ids = [BigInt(99999), BigInt(88888)];
      const result = await repository.batchUpdateStatus(ids, 'suspended');

      expect(result).toBe(0);
    });

    it('should handle mixed existing and non-existent accounts', async () => {
      const ids = [account1.id, BigInt(99999), account2.id];
      const result = await repository.batchUpdateStatus(ids, 'inactive');

      expect(result).toBe(2); // 只有2个存在的账号被更新

      const updated1 = await repository.findById(account1.id);
      const updated2 = await repository.findById(account2.id);

      expect(updated1?.status).toBe('inactive');
      expect(updated2?.status).toBe('inactive');
    });
  });

  describe('getStatusStatistics', () => {
    beforeEach(async () => {
      // 创建不同状态的账号
      await repository.create({
        gameUserId: BigInt(1),
        zulipUserId: 1,
        zulipEmail: 'active1@example.com',
        zulipFullName: '活跃用户1',
        zulipApiKeyEncrypted: 'key1',
        status: 'active',
      });

      await repository.create({
        gameUserId: BigInt(2),
        zulipUserId: 2,
        zulipEmail: 'active2@example.com',
        zulipFullName: '活跃用户2',
        zulipApiKeyEncrypted: 'key2',
        status: 'active',
      });

      await repository.create({
        gameUserId: BigInt(3),
        zulipUserId: 3,
        zulipEmail: 'inactive1@example.com',
        zulipFullName: '非活跃用户1',
        zulipApiKeyEncrypted: 'key3',
        status: 'inactive',
      });

      await repository.create({
        gameUserId: BigInt(4),
        zulipUserId: 4,
        zulipEmail: 'suspended1@example.com',
        zulipFullName: '暂停用户1',
        zulipApiKeyEncrypted: 'key4',
        status: 'suspended',
      });

      await repository.create({
        gameUserId: BigInt(5),
        zulipUserId: 5,
        zulipEmail: 'error1@example.com',
        zulipFullName: '错误用户1',
        zulipApiKeyEncrypted: 'key5',
        status: 'error',
      });
    });

    it('should return correct status statistics', async () => {
      const result = await repository.getStatusStatistics();

      expect(result).toEqual({
        active: 2,
        inactive: 1,
        suspended: 1,
        error: 1,
      });
    });

    it('should return zero statistics for empty repository', async () => {
      // 清空所有数据
      (repository as any).accounts.clear();

      const result = await repository.getStatusStatistics();

      expect(result).toEqual({
        active: 0,
        inactive: 0,
        suspended: 0,
        error: 0,
      });
    });
  });

  describe('existsByEmail', () => {
    let createdAccount: ZulipAccounts;

    beforeEach(async () => {
      createdAccount = await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test@example.com',
        zulipFullName: '测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      });
    });

    it('should return true if email exists', async () => {
      const result = await repository.existsByEmail('test@example.com');

      expect(result).toBe(true);
    });

    it('should return false if email does not exist', async () => {
      const result = await repository.existsByEmail('notfound@example.com');

      expect(result).toBe(false);
    });

    it('should exclude specified ID', async () => {
      const result = await repository.existsByEmail('test@example.com', createdAccount.id);

      expect(result).toBe(false);
    });

    it('should not exclude different ID', async () => {
      const result = await repository.existsByEmail('test@example.com', BigInt(99999));

      expect(result).toBe(true);
    });
  });

  describe('existsByZulipUserId', () => {
    let createdAccount: ZulipAccounts;

    beforeEach(async () => {
      createdAccount = await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test@example.com',
        zulipFullName: '测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      });
    });

    it('should return true if zulip user ID exists', async () => {
      const result = await repository.existsByZulipUserId(67890);

      expect(result).toBe(true);
    });

    it('should return false if zulip user ID does not exist', async () => {
      const result = await repository.existsByZulipUserId(99999);

      expect(result).toBe(false);
    });

    it('should exclude specified ID', async () => {
      const result = await repository.existsByZulipUserId(67890, createdAccount.id);

      expect(result).toBe(false);
    });
  });

  describe('existsByGameUserId', () => {
    let createdAccount: ZulipAccounts;

    beforeEach(async () => {
      createdAccount = await repository.create({
        gameUserId: BigInt(12345),
        zulipUserId: 67890,
        zulipEmail: 'test@example.com',
        zulipFullName: '测试用户',
        zulipApiKeyEncrypted: 'encrypted_api_key',
        status: 'active',
      });
    });

    it('should return true if game user ID exists', async () => {
      const result = await repository.existsByGameUserId(BigInt(12345));

      expect(result).toBe(true);
    });

    it('should return false if game user ID does not exist', async () => {
      const result = await repository.existsByGameUserId(BigInt(99999));

      expect(result).toBe(false);
    });

    it('should exclude specified ID', async () => {
      const result = await repository.existsByGameUserId(BigInt(12345), createdAccount.id);

      expect(result).toBe(false);
    });
  });
});