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

namespace AdsTrackingService.API.Application.Commands;

/// <summary>
/// EN: Handler for TrackPixelEventCommand.
/// VI: Handler cho TrackPixelEventCommand.
/// </summary>
public class TrackPixelEventCommandHandler : IRequestHandler<TrackPixelEventCommand, bool>
{
    private readonly ITrackingPixelRepository _repository;
    private readonly ILogger<TrackPixelEventCommandHandler> _logger;

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

    public async Task<bool> Handle(TrackPixelEventCommand request, CancellationToken ct)
    {
        // EN: Verify pixel exists and is active
        // VI: Xác minh pixel tồn tại và đang hoạt động
        var pixel = await _repository.GetByPixelCodeAsync(request.PixelCode, ct);
        if (pixel == null)
        {
            _logger.LogWarning("Pixel code {PixelCode} not found", request.PixelCode);
            return false;
        }

        if (!pixel.IsActive)
        {
            _logger.LogWarning("Pixel code {PixelCode} is not active", request.PixelCode);
            return false;
        }

        // EN: Create pixel event
        // VI: Tạo pixel event
        var pixelEvent = new PixelEvent(
            pixel.Id,
            request.AdId,
            request.UserId,
            request.EventType,
            request.UserAgent,
            request.IpAddress
        );

        // EN: Note: In a real implementation, you would add PixelEvent to a repository
        // VI: Lưu ý: Trong triển khai thực tế, bạn sẽ thêm PixelEvent vào repository
        // For now, we just log it as PixelEvent is not an aggregate root
        
        _logger.LogInformation(
            "Tracked pixel event: PixelCode={PixelCode}, AdId={AdId}, UserId={UserId}, EventType={EventType}",
            request.PixelCode, request.AdId, request.UserId, request.EventType);

        return true;
    }
}
