import { InstallId } from '../value-objects/install-id.vo';
import { EventName } from '../value-objects/event-name.vo';
import { EventProperties } from '../value-objects/event-properties.vo';

export class EventLog {
  private _id: bigint | null;
  private _userId: string | null;  // userSerialNum, e.g. "D25121400005"
  private _installId: InstallId;
  private _eventName: EventName;
  private _eventTime: Date;
  private _properties: EventProperties;
  private _createdAt: Date;

  private constructor() {}

  // Getters
  get id(): bigint | null {
    return this._id;
  }

  get userId(): string | null {
    return this._userId;
  }

  get installId(): InstallId {
    return this._installId;
  }

  get eventName(): EventName {
    return this._eventName;
  }

  get eventTime(): Date {
    return this._eventTime;
  }

  get properties(): EventProperties {
    return this._properties;
  }

  get createdAt(): Date {
    return this._createdAt;
  }

  /**
   * 获取用于DAU去重的唯一标识
   * 优先使用 userId (userSerialNum)，否则使用 installId
   */
  get dauIdentifier(): string {
    return this._userId ?? this._installId.value;
  }

  // 工厂方法
  static create(props: {
    userId?: string | null;  // userSerialNum, e.g. "D25121400005"
    installId: InstallId;
    eventName: EventName;
    eventTime: Date;
    properties?: EventProperties;
  }): EventLog {
    const log = new EventLog();
    log._id = null;
    log._userId = props.userId ?? null;
    log._installId = props.installId;
    log._eventName = props.eventName;
    log._eventTime = props.eventTime;
    log._properties = props.properties ?? EventProperties.empty();
    log._createdAt = new Date();
    return log;
  }

  // 从持久化恢复
  static reconstitute(props: {
    id: bigint;
    userId: string | null;  // userSerialNum, e.g. "D25121400005"
    installId: InstallId;
    eventName: EventName;
    eventTime: Date;
    properties: EventProperties;
    createdAt: Date;
  }): EventLog {
    const log = new EventLog();
    log._id = props.id;
    log._userId = props.userId;
    log._installId = props.installId;
    log._eventName = props.eventName;
    log._eventTime = props.eventTime;
    log._properties = props.properties;
    log._createdAt = props.createdAt;
    return log;
  }
}
