/**
 * TextValidationPipe
 *
 * NestJS PipeTransform that validates text input for TTS synthesis.
 * Checks that text is non-empty and within the configurable maximum length.
 *
 * Usage:
 * ```typescript
 * @Post('synthesize')
 * async synthesize(
 *   @Body('text', new TextValidationPipe()) text: string,
 * ) { ... }
 * ```
 *
 * Issue #398
 */

import { BadRequestException } from "@nestjs/common";
import type { PipeTransform } from "@nestjs/common";

/**
 * Default maximum text length for TTS input (4096 characters).
 */
const DEFAULT_MAX_TEXT_LENGTH = 4096;

/**
 * Options for customizing TextValidationPipe behavior.
 */
export interface TextValidationPipeOptions {
  /** Maximum text length in characters. Defaults to 4096. */
  maxTextLength?: number;
}

export class TextValidationPipe implements PipeTransform<string | null | undefined> {
  private readonly maxTextLength: number;

  constructor(options?: TextValidationPipeOptions) {
    this.maxTextLength = options?.maxTextLength ?? DEFAULT_MAX_TEXT_LENGTH;
  }

  /**
   * Validate the text input for TTS synthesis.
   *
   * @param text - The text to validate
   * @returns The validated text, unchanged
   * @throws {BadRequestException} If text is empty, whitespace-only, or exceeds the max length
   */
  transform(text: string | null | undefined): string {
    if (text === null || text === undefined) {
      throw new BadRequestException("Text cannot be empty");
    }

    if (text.trim().length === 0) {
      throw new BadRequestException("Text cannot be empty");
    }

    if (text.length > this.maxTextLength) {
      throw new BadRequestException(
        `Text length ${String(text.length)} exceeds maximum allowed length of ${String(this.maxTextLength)} characters`
      );
    }

    return text;
  }
}
