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

namespace Application.Endpoints.Pacients.ResetPassword;

public class PacientResetPasswordHandler
{
    private readonly IPacientRepository _pacientRepository;

    public PacientResetPasswordHandler(IPacientRepository pacientRepository)
    {
        _pacientRepository = pacientRepository;
    }

    public async Task<BaseResponse> Handle(PacientLoginDTO resetPacientDto)
    {
        var validation = new PacientResetPasswordValidation(_pacientRepository);
        var validationResult = await validation.ValidateAsync(resetPacientDto);

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

        var currentPacient = await _pacientRepository.FindByEmailAsync(resetPacientDto.Email);

        var updatedPacient = currentPacient;

        updatedPacient.Password = resetPacientDto.Password;

        await _pacientRepository.UpdateAsync(updatedPacient);

        updatedPacient = await _pacientRepository.GetByIdAsync(currentPacient.Id);

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

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