// EN: Handler for DeactivateTherapistCommand.
// VI: Handler cho DeactivateTherapistCommand.

using BookingService.Domain.AggregatesModel.TherapistAggregate;
using BookingService.Domain.Exceptions;
using MediatR;

namespace BookingService.API.Application.Commands.Therapist;

/// <summary>
/// EN: Handler for deactivating a therapist.
/// VI: Handler để vô hiệu hóa chuyên viên.
/// </summary>
public class DeactivateTherapistCommandHandler : IRequestHandler<DeactivateTherapistCommand, bool>
{
    private readonly ITherapistRepository _therapistRepository;
    private readonly ILogger<DeactivateTherapistCommandHandler> _logger;

    public DeactivateTherapistCommandHandler(
        ITherapistRepository therapistRepository,
        ILogger<DeactivateTherapistCommandHandler> logger)
    {
        _therapistRepository = therapistRepository ?? throw new ArgumentNullException(nameof(therapistRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<bool> Handle(DeactivateTherapistCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Deactivating therapist {TherapistId} / Vô hiệu hóa chuyên viên {TherapistId}",
            request.TherapistId);

        // EN: Load therapist from repository
        // VI: Load chuyên viên từ repository
        var therapist = await _therapistRepository.GetByIdAsync(request.TherapistId, cancellationToken);
        if (therapist == null)
        {
            throw new DomainException($"Therapist {request.TherapistId} not found / Không tìm thấy chuyên viên {request.TherapistId}");
        }

        // EN: Deactivate via domain behavior method
        // VI: Vô hiệu hóa qua phương thức hành vi domain
        therapist.Deactivate();

        // EN: Save changes
        // VI: Lưu thay đổi
        _therapistRepository.Update(therapist);
        await _therapistRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation(
            "Deactivated therapist {TherapistId} / Đã vô hiệu hóa chuyên viên {TherapistId}",
            therapist.Id);

        return true;
    }
}
