import { Injectable, type PipeTransform, UnprocessableEntityException } from '@nestjs/common';

@Injectable()
export class Uint32Pipe implements PipeTransform<string, number> {
  /**
   * 静态 transform 方法 (用于装饰器)
   * @param value - 待验证的值
   */
  public transform(value: unknown): number {
    if (value === undefined || value === null || value === '') {
      throw new UnprocessableEntityException('参数不能为空');
    }

    if ((typeof value === 'string' && !/^\d+$/.test(value)) || isNaN(Number(value))) {
      throw new UnprocessableEntityException('参数必须是数字');
    }

    const num = Number(value);
    if (!Number.isSafeInteger(num)) {
      throw new UnprocessableEntityException('参数超出安全整数范围');
    } else if (num < 0 || num > 4294967295) {
      throw new UnprocessableEntityException('参数必须在 0 到 4294967295 之间');
    }
    return num;
  }
}
