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

@Injectable()
export class Uint32Pipe implements PipeTransform<string, number> {
  public constructor(
    private readonly name?: string,
    private readonly code: 422 | 423 = 422
  ) {}

  public transform(value: unknown): number {
    const field = this.name ?? '参数';
    if (value === undefined || value === null || value === '') {
      const message = `${field}不能为空`;
      if (this.code === 422) {
        throw new UnprocessableEntityException(message);
      }
      throw new HttpException(message, 423);
    }

    if ((typeof value === 'string' && !/^\d+$/.test(value)) || isNaN(Number(value))) {
      const message = `${field}必须是数字`;
      if (this.code === 422) {
        throw new UnprocessableEntityException(message);
      }
      throw new HttpException(message, 423);
    }

    const num = Number(value);
    if (!Number.isSafeInteger(num)) {
      const message = `${field}超出安全整数范围`;
      if (this.code === 422) {
        throw new UnprocessableEntityException(message);
      }
      throw new HttpException(message, 423);
    } else if (num < 0 || num > 4294967295) {
      const message = `${field}必须在0到4294967295之间`;
      if (this.code === 422) {
        throw new UnprocessableEntityException(message);
      }
      throw new HttpException(message, 423);
    }
    return num;
  }
}
