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

namespace IWS5.Services.Validators;

public class UpdateDocumentFieldsRequestValidator : AbstractValidator<UpdateDocumentFieldListRequest>
{
    public UpdateDocumentFieldsRequestValidator(IDocumentCabinetRepository documentCabinetRepository,
        IDocumentRepository documentRepository)
    {
        RuleFor(x => x.DocumentId)
            .GreaterThan(0).WithMessage("Document ID is required and must be greater than 0.")
            .Must(documentId => documentRepository.AnyAsync(document => document.DocumentId == documentId).Result)
            .WithMessage("Document ID must be among existing [dbo].[ATDocument].DocumentId records.");

        RuleFor(x => x.DocumentTemplateName)
            .NotNull().NotEmpty().WithMessage("Document Template name is required and should not be empty.");

        RuleFor(x => x)
            .Must(x => documentCabinetRepository
                .AnyAsync(cabinet =>
                    cabinet.CabinetName == x.DocumentTemplateName && cabinet.CabinetId == x.DocumentTemplateId).Result)
            .WithMessage(x =>
                $"Document template with combination of Document Template Name '{x.DocumentTemplateName}' and Document Template ID '{x.DocumentTemplateId}' does not exist.");

        RuleFor(x => x.FieldsToUpdate)
            .NotEmpty()
            .WithMessage("At least one field is required.")
            
            .ForEach(field =>
                field.Must(fieldItem => TypeHelpers.IsParsable(fieldItem.FieldType, fieldItem.FieldValue))
                    .WithMessage((fields, fieldItem) =>
                        $"Field value '{fieldItem.FieldValue}' is not parsable to '{fieldItem.FieldType}' type."));
    }
}