// custom-validation.pipe.ts
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
import { CustomException } from './custom.exception';

@Injectable()
export class CustomValidationPipe implements PipeTransform {
    constructor(private readonly schema) { }

    transform(value: any, metadata: ArgumentMetadata) {
        const errors = this.validate(value, this.schema);
        if (errors.length) {
            throw new CustomException(errors);
        }
        return value;
    }

    validate(value: any, schema: any): string[] {
        const errors = [];
        for (const key in schema) {
            if (schema[key].includes('required') && !(key in value)) {
                errors.push(`${key} is required`);
            }
            if (schema[key].includes('alpha_only') && typeof value[key] !== 'string') {
                errors.push(`${key} must be a string`);
            }
            if (schema[key].includes('digits_only') && typeof value[key] !== 'number') {
                errors.push(`${key} must be a number`);
            }
        }
        return errors;
    }
}
