import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';
import { isSupportedCountry } from 'libphonenumber-js';

export function IsCountryCode(validationOptions?: ValidationOptions) {
    return (object: unknown, propertyName: string) => {
        registerDecorator({
            options: validationOptions,
            propertyName,
            target: object?.constructor as (...args: any) => any,
            validator: IsCountryCodeConstraint,
        });
    };
}

@ValidatorConstraint({ name: 'IsCountryCode' })
class IsCountryCodeConstraint implements ValidatorConstraintInterface {
    validate(value: any): boolean {
        if (!value || typeof value !== 'string') return false;
        return isSupportedCountry(value);
    }

    defaultMessage(args?: ValidationArguments): string {
        const propertyName = args?.property as string;
        return `${propertyName} must be a valid country code`;
    }
}
