import { DomainException } from '../../shared/exceptions/domain.exception';

/**
 * 文件大小值对象 (字节)
 */
export class FileSize {
  private readonly _bytes: bigint;

  private constructor(bytes: bigint) {
    this._bytes = bytes;
  }

  get bytes(): bigint {
    return this._bytes;
  }

  static create(bytes: bigint | number): FileSize {
    const value = typeof bytes === 'number' ? BigInt(bytes) : bytes;

    if (value < 0n) {
      throw new DomainException('FileSize cannot be negative');
    }

    // 最大文件大小: 2GB
    const maxSize = BigInt(2) * BigInt(1024) * BigInt(1024) * BigInt(1024);
    if (value > maxSize) {
      throw new DomainException('FileSize cannot exceed 2GB');
    }

    return new FileSize(value);
  }

  /**
   * 转换为人类可读格式
   */
  toHumanReadable(): string {
    const bytes = Number(this._bytes);
    const units = ['B', 'KB', 'MB', 'GB'];
    let size = bytes;
    let unitIndex = 0;

    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }

    return `${size.toFixed(2)} ${units[unitIndex]}`;
  }

  equals(other: FileSize): boolean {
    return this._bytes === other._bytes;
  }

  toString(): string {
    return this._bytes.toString();
  }
}
