using FluentValidation;
using IWS5.Core.Enums;
using IWS5.Core.Models.Request;
using IWS5.DatabaseAccess.Interfaces;

namespace IWS5.Services.Validators;

public class CreateDocumentTemplateRequestValidator : AbstractValidator<CreateDocumentTemplateRequest>
{
    public CreateDocumentTemplateRequestValidator(IDocumentCabinetRepository documentCabinetRepository)
    {
        RuleFor(x => x.TemplateName)
            .NotEmpty().WithMessage("Template name is required.")
            .MaximumLength(100).WithMessage("Template name must not exceed 100 characters.")
            .Must(templateName =>
            {
                var exists = documentCabinetRepository.AnyAsync(dc => dc.CabinetName == templateName).Result;
                return !exists;
            })
            .WithMessage("A database with the same name already exists.");

        RuleFor(x => x.Description)
            .NotEmpty().WithMessage("Description is required.")
            .MaximumLength(500).WithMessage("Description must not exceed 500 characters.");

        RuleFor(x => x.TemplateType)
            .IsInEnum().WithMessage("Invalid template type.");

        When(x => x.TemplateType == ATTemplateType.Document, () =>
        {
            RuleFor(x => x.DataConnectionId)
                .Null().WithMessage("Data connection ID must be null for Document template type.");

            RuleFor(x => x.DatabaseName)
                .Null().WithMessage("Database name must be null for Document template type.");
        });

        When(x => x.TemplateType != ATTemplateType.Document, () =>
        {
            RuleFor(x => x.DataConnectionId)
                .NotNull().WithMessage("Data connection ID is required.")
                .GreaterThan(0).WithMessage("Data connection ID is required and must be greater than 0.");

            RuleFor(x => x.DatabaseName)
                .NotNull().WithMessage("Database name is required.")
                .NotEmpty().WithMessage("Database name is required.");
        });

        RuleFor(x => x.Fields)
            .NotEmpty().WithMessage("At least one field is required.")
            .ForEach(field => field.SetValidator(new DocumentTemplateFieldValidator()));
    }
}
