using Application.Endpoints.Doctors.Login;
using Application.Services.Database;

namespace Application.Endpoints.Doctors.ResetPassword;

public class DoctorResetPasswordHandler
{
    private readonly IDoctorRepository _doctorRepository;

    public DoctorResetPasswordHandler(IDoctorRepository doctorRepository)
    {
        _doctorRepository = doctorRepository;
    }

    public async Task<BaseResponse> Handle(DoctorLoginDTO resetDoctorDto)
    {
        var validation = new DoctorResetPasswordValidation(_doctorRepository);
        var validationResult = await validation.ValidateAsync(resetDoctorDto);

        if (!validationResult.IsValid)
        {
            var errorMessage = validationResult.Errors.Select(e => e.ErrorMessage).ToList();
            return new BaseResponse
            {
                Success = false,
                Message = string.Join(", ", errorMessage),
                Data = null
            };
        }

        var currentDoctor = await _doctorRepository.FindByEmailAsync(resetDoctorDto.Email);

        var updatedDoctor = currentDoctor;

        updatedDoctor.Password = resetDoctorDto.Password;

        await _doctorRepository.UpdateAsync(updatedDoctor);

        updatedDoctor = await _doctorRepository.GetByIdAsync(currentDoctor.Id);

        if (updatedDoctor.Password != resetDoctorDto.Password)
        {
            return new BaseResponse
            {
                Success = false,
                Message = $"Failed to update passwor for doctor {updatedDoctor.Name}",
                Data = null
            };
        }

        return new BaseResponse
        {
            Success = true,
            Message = $"Password of doctor {updatedDoctor.Name} has been reset succesfully",
            Data = updatedDoctor.Email
        };
    }
}
