using MediatR;
using AdsAnalyticsService.Domain.AggregatesModel.ReportAggregate;
using AdsAnalyticsService.Infrastructure;

namespace AdsAnalyticsService.API.Application.Commands;

/// <summary>
/// EN: Handler for CreateReportCommand.
/// VI: Handler cho CreateReportCommand.
/// </summary>
public class CreateReportCommandHandler : IRequestHandler<CreateReportCommand, Guid>
{
    private readonly AdsAnalyticsServiceContext _context;
    private readonly ILogger<CreateReportCommandHandler> _logger;

    public CreateReportCommandHandler(
        AdsAnalyticsServiceContext context,
        ILogger<CreateReportCommandHandler> logger)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<Guid> Handle(CreateReportCommand request, CancellationToken cancellationToken)
    {
        // EN: Create report aggregate
        // VI: Tạo report aggregate
        var report = new Report(
            request.AdvertiserId,
            request.Name,
            request.ReportType,
            request.StartDate,
            request.EndDate);

        // EN: Add to context
        // VI: Thêm vào context
        await _context.Reports.AddAsync(report, cancellationToken);
        await _context.SaveChangesAsync(cancellationToken);

        _logger.LogInformation("Created report {ReportId} for advertiser {AdvertiserId}", 
            report.Id, request.AdvertiserId);

        return report.Id;
    }
}
