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

namespace Application.Endpoints.Patients.Registration;

public class PatientRegistrationHandler
{
    private readonly IHashingAlgorithms _hashingAlgorithms;
    private readonly IPatientRepository _patientRepository;

    public PatientRegistrationHandler(IPatientRepository patientRepository, IHashingAlgorithms hashingAlgorithms)
    {
        _patientRepository = patientRepository;
        _hashingAlgorithms = hashingAlgorithms;
    }

    public async Task<BaseResponse> Handle(PatientRegistrationDto registrationDTO)
    {
        var validation = new PatientRegistrationValidation(_patientRepository);
        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 patient = new Patient();
        patient.SetEmail(registrationDTO.Email);
        patient.SetName(registrationDTO.Name);
        patient.SetPassword(_hashingAlgorithms.SHA256Algorithm(registrationDTO.Password));

        await _patientRepository.AddAsync(patient);

        return new BaseResponse
        {
            StatusCode = HttpStatusCodes.Created,
            Message = "Patient registered successfully",
            Data = patient // Be careful with sending sensitive data like Passwords
        };
    }
}