/**
 * Sanitize Decorator
 *
 * Custom class-validator decorator to sanitize string input and prevent XSS.
 */

import { Transform } from "class-transformer";
import { sanitizeString, sanitizeObject } from "../utils/sanitize.util";

/**
 * Sanitize decorator for DTO properties
 * Automatically sanitizes string values to prevent XSS attacks
 *
 * Usage:
 * ```typescript
 * class MyDto {
 *   @Sanitize()
 *   @IsString()
 *   userInput!: string;
 * }
 * ```
 */
export function Sanitize(): PropertyDecorator {
  return Transform(({ value }: { value: unknown }) => {
    if (typeof value === "string") {
      return sanitizeString(value);
    }
    return value;
  });
}

/**
 * SanitizeObject decorator for nested objects
 * Recursively sanitizes all string values in an object
 *
 * Usage:
 * ```typescript
 * class MyDto {
 *   @SanitizeObject()
 *   @IsObject()
 *   metadata?: Record<string, unknown>;
 * }
 * ```
 */
export function SanitizeObject(): PropertyDecorator {
  return Transform(({ value }: { value: unknown }) => {
    if (typeof value === "object" && value !== null) {
      return sanitizeObject(value as Record<string, unknown>);
    }
    return value;
  });
}
