using MediatR;
using WhatsAppService.Domain.AggregatesModel.SampleAggregate;

namespace WhatsAppService.API.Application.Commands;

/// <summary>
/// EN: Handler for UpdateSampleCommand.
/// VI: Handler cho UpdateSampleCommand.
/// </summary>
public class UpdateSampleCommandHandler : IRequestHandler<UpdateSampleCommand, bool>
{
    private readonly ISampleRepository _sampleRepository;
    private readonly ILogger<UpdateSampleCommandHandler> _logger;

    public UpdateSampleCommandHandler(
        ISampleRepository sampleRepository,
        ILogger<UpdateSampleCommandHandler> logger)
    {
        _sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<bool> Handle(
        UpdateSampleCommand request,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Updating sample {SampleId} / Cập nhật sample {SampleId}",
            request.SampleId);

        // EN: Get existing sample / VI: Lấy sample đã tồn tại
        var sample = await _sampleRepository.GetAsync(request.SampleId);

        if (sample is null)
        {
            _logger.LogWarning(
                "Sample {SampleId} not found / Sample {SampleId} không tìm thấy",
                request.SampleId);
            return false;
        }

        // EN: Update sample using domain method / VI: Cập nhật sample sử dụng domain method
        sample.Update(request.Name, request.Description);

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

        _logger.LogInformation(
            "Sample {SampleId} updated successfully / Sample {SampleId} đã cập nhật thành công",
            request.SampleId);

        return true;
    }
}
