using FluentValidation;
using IWS5.Core.Enums;
using IWS5.Core.Helpers;
using IWS5.Core.Models.Request;

namespace IWS5.Services.Validators;

public class DocumentTemplateFieldValidator : AbstractValidator<DocumentTemplateField>
{
    public DocumentTemplateFieldValidator()
    {
        RuleFor(x => x.Name)
            .NotEmpty().WithMessage("Field name is required.")
            .MaximumLength(255).WithMessage("Field name must not exceed 255 characters.");

        RuleFor(x => x.FieldType)
            .IsInEnum().WithMessage("Invalid field type.");

        RuleFor(x => x.DefaultValue)
            .NotNull()
            .NotEmpty()
            .When(x => !x.IsNullable)
            .WithMessage("Default value is required when the field is not nullable.");
        
        RuleFor(x => x.DefaultValue)
            .MaximumLength(255)
            .When(x => x.FieldType == ATDocumentFieldType.String)
            .WithMessage("Default value must not exceed 255 characters for String type.");

        RuleFor(x => x.DefaultValue)
            .Must((field, defaultValue) =>
            {
                if (string.IsNullOrEmpty(defaultValue))
                    return true;

                return TypeHelpers.IsParsable(field.FieldType, defaultValue);
            })
            .WithMessage(field =>
                $"Default value {field.DefaultValue} for field '{field.Name}' does not match the field type {field.FieldType.ToString()}.");
    }
}