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

namespace Application.Endpoints.Doctors.Login;

public class DoctorLoginHandler
{
    private readonly IDoctorRepository _database;
    private readonly IHashingAlgorithms _hashingAlgorithms;

    public DoctorLoginHandler(IDoctorRepository database, IHashingAlgorithms hashingAlgorithms)
    {
        _database = database;
        _hashingAlgorithms = hashingAlgorithms;
    }

    public async Task<BaseResponse> Handle(DoctorLoginDto loginDTO)
    {
        loginDTO.Password = _hashingAlgorithms.SHA256Algorithm(loginDTO.Password);

        var validation = new DoctorLoginValidation(_database);
        var validationResult = await validation.ValidateAsync(loginDTO);

        if (validationResult.IsValid)
            return new BaseResponse
            {
                StatusCode = HttpStatusCodes.OK,
                Message = "Authentication successful",
                Data = null
            };

        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
        };
    }
}