using MediatR;
using AdsTrackingService.Domain.AggregatesModel.TrackingPixelAggregate;

namespace AdsTrackingService.API.Application.Commands;

/// <summary>
/// EN: Handler for CreateTrackingPixelCommand.
/// VI: Handler cho CreateTrackingPixelCommand.
/// </summary>
public class CreateTrackingPixelCommandHandler : IRequestHandler<CreateTrackingPixelCommand, TrackingPixelResult>
{
    private readonly ITrackingPixelRepository _repository;
    private readonly ILogger<CreateTrackingPixelCommandHandler> _logger;

    public CreateTrackingPixelCommandHandler(
        ITrackingPixelRepository repository,
        ILogger<CreateTrackingPixelCommandHandler> _logger)
    {
        _repository = repository ?? throw new ArgumentNullException(nameof(repository));
        this._logger = _logger ?? throw new ArgumentNullException(nameof(_logger));
    }

    public async Task<TrackingPixelResult> Handle(CreateTrackingPixelCommand request, CancellationToken ct)
    {
        // EN: Check if pixel already exists for this advertiser
        // VI: Kiểm tra xem pixel đã tồn tại cho advertiser này chưa
        var existingPixel = await _repository.GetByAdvertiserIdAsync(request.AdvertiserId, ct);
        if (existingPixel != null)
        {
            _logger.LogInformation(
                "Tracking pixel already exists for advertiser {AdvertiserId}, returning existing pixel {PixelCode}",
                request.AdvertiserId, existingPixel.PixelCode);
            
            return new TrackingPixelResult(existingPixel.Id, existingPixel.PixelCode, existingPixel.IsActive);
        }

        // EN: Create new tracking pixel
        // VI: Tạo tracking pixel mới
        var pixel = new TrackingPixel(request.AdvertiserId);
        
        await _repository.AddAsync(pixel, ct);
        await _repository.UnitOfWork.SaveEntitiesAsync(ct);

        _logger.LogInformation(
            "Created tracking pixel {PixelCode} for advertiser {AdvertiserId}",
            pixel.PixelCode, pixel.AdvertiserId);

        return new TrackingPixelResult(pixel.Id, pixel.PixelCode, pixel.IsActive);
    }
}
