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

@Injectable()
export class NonEmptyStringPipe implements PipeTransform<string, string> {
  public constructor(
    private readonly name?: string,
    private readonly code: 422 | 423 = 422
  ) {}
  public transform(value: unknown): string {
    if (typeof value !== 'string' || value.trim().length === 0) {
      const message = `${this.name ?? '参数'}不能为空`;
      if (this.code === 422) {
        throw new UnprocessableEntityException(message);
      }
      throw new HttpException(message, 423);
    }
    return value.trim();
  }
}
