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 deleting (archiving) a campaign.
/// VI: Handler cho việc xóa (lưu trữ) chiến dịch.
/// </summary>
public class DeleteCampaignCommandHandler : IRequestHandler<DeleteCampaignCommand, bool>
{
    private readonly ICampaignRepository _campaignRepository;
    private readonly IUnitOfWork _unitOfWork;
    private readonly ILogger<DeleteCampaignCommandHandler> _logger;

    public DeleteCampaignCommandHandler(
        ICampaignRepository campaignRepository,
        IUnitOfWork unitOfWork,
        ILogger<DeleteCampaignCommandHandler> 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(DeleteCampaignCommand 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: Archive campaign (soft delete)
        // VI: Lưu trữ chiến dịch (soft delete)
        campaign.Archive();

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

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

        return true;
    }
}
