using MediatR;
using AdsTrackingService.Domain.AggregatesModel.ConversionAggregate;

namespace AdsTrackingService.API.Application.Commands;

/// <summary>
/// EN: Handler for RecordConversionCommand.
/// VI: Handler cho RecordConversionCommand.
/// </summary>
public class RecordConversionCommandHandler : IRequestHandler<RecordConversionCommand, ConversionResult>
{
    private readonly IConversionRepository _repository;
    private readonly ILogger<RecordConversionCommandHandler> _logger;

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

    public async Task<ConversionResult> Handle(RecordConversionCommand request, CancellationToken ct)
    {
        // EN: Create conversion
        // VI: Tạo conversion
        var conversion = new Conversion(
            request.AdvertiserId,
            request.CampaignId,
            request.UserId,
            request.ConversionType,
            request.ConversionValue,
            request.Currency
        );

        await _repository.AddAsync(conversion, ct);
        await _repository.UnitOfWork.SaveEntitiesAsync(ct);

        _logger.LogInformation(
            "Recorded conversion: Id={ConversionId}, Campaign={CampaignId}, Type={ConversionType}, Value={Value} {Currency}",
            conversion.Id, conversion.CampaignId, conversion.ConversionType, conversion.ConversionValue, conversion.Currency);

        return new ConversionResult(conversion.Id, conversion.ConversionTime);
    }
}
