using Application.Services.Database;
using FluentValidation;

namespace Application.Endpoints.MedicalHistories.FileManagement;

public class MedicalHistoryCreateValidation : AbstractValidator<MedicalHistoryCreateDto>
{
    private readonly IPatientRepository _patientRepository;

    public MedicalHistoryCreateValidation(IPatientRepository patientRepository)
    {
        _patientRepository = patientRepository;

        RuleFor(x => x.UserId)
            .NotEmpty().WithMessage("Patient is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
            .MustAsync(BeExistingUser).WithMessage("Specified patient doesn't exist.")
            .WithErrorCode(HttpStatusCodes.NotFound.ToString());

        RuleFor(x => x.Content)
            .NotEmpty().WithMessage("Description is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString());
    }

    private async Task<bool> BeExistingUser(Guid userId, CancellationToken cancellationToken)
    {
        var patient = await _patientRepository.GetByIdAsync(userId);
        return patient != null;
    }
}