using AdsManagerService.Domain.AggregatesModel.CampaignAggregate;
using AdsManagerService.Domain.SeedWork;
using AdsManagerService.Infrastructure;
using MediatR;
using Microsoft.Extensions.Logging;

namespace AdsManagerService.API.Application.Commands;

/// <summary>
/// EN: Handler for pausing a campaign.
/// VI: Handler cho việc tạm dừng chiến dịch.
/// </summary>
public class PauseCampaignCommandHandler : IRequestHandler<PauseCampaignCommand, bool>
{
    private readonly ICampaignRepository _campaignRepository;
    private readonly IUnitOfWork _unitOfWork;
    private readonly ILogger<PauseCampaignCommandHandler> _logger;

    public PauseCampaignCommandHandler(
        ICampaignRepository campaignRepository,
        IUnitOfWork unitOfWork,
        ILogger<PauseCampaignCommandHandler> logger)
    {
        _campaignRepository = campaignRepository ?? throw new ArgumentNullException(nameof(campaignRepository));
        _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<bool> Handle(PauseCampaignCommand request, CancellationToken cancellationToken)
    {
        // EN: Get campaign
        // VI: Lấy chiến dịch
        var campaign = await _campaignRepository.GetByIdAsync(request.CampaignId);

        if (campaign == null)
        {
            _logger.LogWarning("Campaign {CampaignId} not found", request.CampaignId);
            return false;
        }

        // EN: Pause campaign (domain logic handles validation)
        // VI: Tạm dừng chiến dịch (domain logic xử lý validation)
        campaign.Pause();

        // EN: Save changes
        // VI: Lưu thay đổi
        await _unitOfWork.SaveChangesAsync(cancellationToken);

        _logger.LogInformation("Campaign {CampaignId} paused successfully", request.CampaignId);

        return true;
    }
}
