using Application.Services.Database;
using Application.Services.HashingAlgorithms;
using Core.Entities;

namespace Application.Endpoints.Doctors.Registration;

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

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

    public async Task<BaseResponse> Handle(DoctorRegistrationDto registrationDTO)
    {
        var validation = new DoctorRegistrationValidation(_doctorRepository);
        var validationResult = await validation.ValidateAsync(registrationDTO);

        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 doctor = new Doctor();
        doctor.SetEmail(registrationDTO.Email);
        doctor.SetPassword(_hashingAlgorithms.SHA256Algorithm(registrationDTO.Password));
        doctor.SetName(registrationDTO.Name);
        doctor.SetDescription(registrationDTO.Description);

        await _doctorRepository.AddAsync(doctor);

        return new BaseResponse
        {
            StatusCode = HttpStatusCodes.Created,
            Message = "Doctor registered successfully",
            Data = null
        };
    }
}