import { UserAccount } from './user-account.aggregate';
import { AccountSequence } from '@/domain/value-objects';
import { DomainError } from '@/shared/exceptions/domain.exception';

describe('UserAccount', () => {
  const createTestAccount = () => {
    return UserAccount.createAutomatic({
      accountSequence: AccountSequence.create('D2512140001'),
      initialDeviceId: 'device-001',
      deviceName: 'Test Device',
      inviterSequence: null,
    });
  };

  describe('createAutomatic', () => {
    it('should create account with default values', () => {
      const account = createTestAccount();
      expect(account.accountSequence.value).toBe('D2512140001');
      expect(account.nickname).toBe('用户1');
      expect(account.isActive).toBe(true);
      expect(account.phoneNumber).toBeNull();
    });

    it('should add initial device', () => {
      const account = createTestAccount();
      expect(account.isDeviceAuthorized('device-001')).toBe(true);
      expect(account.getAllDevices()).toHaveLength(1);
    });
  });

  describe('addDevice', () => {
    it('should add new device', () => {
      const account = createTestAccount();
      account.addDevice('device-002', 'New Device');
      expect(account.getAllDevices()).toHaveLength(2);
    });

    it('should throw error when exceeding device limit', () => {
      const account = createTestAccount();
      account.addDevice('device-002');
      account.addDevice('device-003');
      account.addDevice('device-004');
      account.addDevice('device-005');

      expect(() => account.addDevice('device-006')).toThrow(DomainError);
    });
  });

  describe('removeDevice', () => {
    it('should remove existing device', () => {
      const account = createTestAccount();
      account.addDevice('device-002');
      account.removeDevice('device-002');
      expect(account.getAllDevices()).toHaveLength(1);
    });

    it('should not remove last device', () => {
      const account = createTestAccount();
      expect(() => account.removeDevice('device-001')).toThrow(DomainError);
    });
  });

  describe('freeze/unfreeze', () => {
    it('should freeze active account', () => {
      const account = createTestAccount();
      account.freeze('Test reason');
      expect(account.isActive).toBe(false);
    });

    it('should unfreeze frozen account', () => {
      const account = createTestAccount();
      account.freeze('Test reason');
      account.unfreeze();
      expect(account.isActive).toBe(true);
    });
  });
});
