using Application.Services.Database;

namespace Application.Endpoints.Patients.Login;

public class PatientLoginHandler
{
    private readonly IPatientRepository _database;

    public PatientLoginHandler(IPatientRepository database)
    {
        _database = database;
    }

    public async Task<BaseResponse> Handle(PatientLoginDto loginDTO)
    {
        var validation = new PatientLoginValidation(_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
        };
    }
}