using Application.Services.Database;
using FluentValidation;

namespace Application.Endpoints.MedicalHistories.ManageAuthorization;

public class MedicalHistoryManageAuthorizationValidation : AbstractValidator<MedicalHistoryManageAuthorizationDoctorDto>
{
    private readonly IMedicalHistoryRepository _medicalHistoryRepository;
    private readonly IDoctorRepository _doctorRepository;

    public MedicalHistoryManageAuthorizationValidation(IMedicalHistoryRepository medicalHistoryRepository,
        IDoctorRepository doctorRepository)
    {
        RuleFor(x => x.MedicalRecordId)
            .NotEmpty().WithMessage("Id is required").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
            .MustAsync(BeExistingMedicalHistoryRecord).WithMessage("Medical history record does not exist")
            .WithErrorCode(HttpStatusCodes.NotFound.ToString());

        RuleFor(x => x.DoctorId)
            .NotEmpty().WithMessage("Id is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
            .MustAsync(IsDoctorRegistered).WithMessage("Doctor is not registered in system")
            .WithErrorCode(HttpStatusCodes.NotFound.ToString());

        _medicalHistoryRepository = medicalHistoryRepository;
        _doctorRepository = doctorRepository;
    }

    private async Task<bool> BeExistingMedicalHistoryRecord(Guid guid, CancellationToken token)
    {
        var record = await _medicalHistoryRepository.GetByIdAsync(guid);
        return record != null;
    }

    private async Task<bool> IsDoctorRegistered(Guid id, CancellationToken cancellationToken)
    {
        var doctor = await _doctorRepository.GetByIdAsync(id);
        return doctor != null;
    }
}