/**
 * Twitter Snowflake 算法
 */
class Snowflake {
  constructor(machineId = 0) {
    this.machineId = machineId; // 机器 ID
    this.sequence = 0; // 序列号
    this.lastTimestamp = -1; // 上次时间戳
  }

  nextId() {
    let timestamp = Date.now();

    if (timestamp === this.lastTimestamp) {
      // 同一毫秒内生成多个 ID
      this.sequence = (this.sequence + 1) & 4095; // 序列号最大 4095
      if (this.sequence === 0) {
        // 序列号用尽,等待下一毫秒
        timestamp = this.waitNextMillis(timestamp);
      }
    } else {
      this.sequence = 0; // 新的一毫秒,重置序列号
    }

    this.lastTimestamp = timestamp;

    // 生成 ID(时间戳 + 机器 ID + 序列号)
    const id = (BigInt(timestamp) << 22n) | (BigInt(this.machineId) << 12n) | BigInt(this.sequence);

    return id.toString();
  }

  waitNextMillis(timestamp) {
    while (timestamp <= this.lastTimestamp) {
      timestamp = Date.now();
    }
    return timestamp;
  }
}
module.exports = Snowflake;