/**
 * User Type Enum
 */
export enum UserType {
  ANONYMOUS = 'ANONYMOUS',
  REGISTERED = 'REGISTERED',
}

/**
 * User Domain Entity
 * Pure domain object without infrastructure dependencies
 */
export class UserEntity {
  readonly id: string;
  type: UserType;
  fingerprint: string | null;
  phone: string | null;
  nickname: string | null;
  avatar: string | null;
  readonly createdAt: Date;
  updatedAt: Date;
  lastActiveAt: Date;

  private constructor(props: {
    id: string;
    type: UserType;
    fingerprint: string | null;
    phone: string | null;
    nickname: string | null;
    avatar: string | null;
    createdAt: Date;
    updatedAt: Date;
    lastActiveAt: Date;
  }) {
    this.id = props.id;
    this.type = props.type;
    this.fingerprint = props.fingerprint;
    this.phone = props.phone;
    this.nickname = props.nickname;
    this.avatar = props.avatar;
    this.createdAt = props.createdAt;
    this.updatedAt = props.updatedAt;
    this.lastActiveAt = props.lastActiveAt;
  }

  /**
   * Create a new anonymous user
   */
  static createAnonymous(fingerprint: string): UserEntity {
    const now = new Date();
    return new UserEntity({
      id: crypto.randomUUID(),
      type: UserType.ANONYMOUS,
      fingerprint,
      phone: null,
      nickname: null,
      avatar: null,
      createdAt: now,
      updatedAt: now,
      lastActiveAt: now,
    });
  }

  /**
   * Reconstruct from persistence
   */
  static fromPersistence(props: {
    id: string;
    type: string;
    fingerprint: string | null;
    phone: string | null;
    nickname: string | null;
    avatar: string | null;
    createdAt: Date;
    updatedAt: Date;
    lastActiveAt: Date;
  }): UserEntity {
    return new UserEntity({
      ...props,
      type: props.type as UserType,
    });
  }

  /**
   * Upgrade user to registered status
   */
  upgradeToRegistered(phone: string): void {
    this.type = UserType.REGISTERED;
    this.phone = phone;
    this.updatedAt = new Date();
  }

  /**
   * Update profile information
   */
  updateProfile(data: { nickname?: string; avatar?: string }): void {
    if (data.nickname !== undefined) {
      this.nickname = data.nickname;
    }
    if (data.avatar !== undefined) {
      this.avatar = data.avatar;
    }
    this.updatedAt = new Date();
  }

  /**
   * Update last active timestamp
   */
  updateLastActive(): void {
    this.lastActiveAt = new Date();
  }

  /**
   * Check if user is registered
   */
  isRegistered(): boolean {
    return this.type === UserType.REGISTERED;
  }
}
