using Application.Services.Database;
using Application.Services.HashingAlgorithms;

namespace Application.Endpoints.Doctors.ResetPassword;

public class DoctorResetPasswordHandler
{
    private readonly IDoctorRepository _doctorRepository;
    private readonly IHashingAlgorithms _hashingAlgorithms;

    public DoctorResetPasswordHandler(IDoctorRepository doctorRepository, IHashingAlgorithms hashingAlgorithms)
    {
        _doctorRepository = doctorRepository;
        _hashingAlgorithms = hashingAlgorithms;
    }

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

        if (!validationResult.IsValid)
        {
            var firstError = validationResult.Errors.FirstOrDefault();
            var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
            var errorMessage = firstError.ErrorMessage;

            return new BaseResponse
            {
                StatusCode = errorCode,
                Message = errorMessage,
                Data = null
            };
        }

        var currentDoctor = await _doctorRepository.FindByEmailAsync(resetDoctorDto.Email);
        var updatedDoctor = currentDoctor;
        updatedDoctor.SetPassword(_hashingAlgorithms.SHA256Algorithm(resetDoctorDto.Password));

        await _doctorRepository.UpdateAsync(updatedDoctor);

        return new BaseResponse
        {
            StatusCode = HttpStatusCodes.OK,
            Message = "Password successfully changed!",
            Data = null
        };
    }
}