using AdsManagerService.Domain.AggregatesModel.AdAggregate;
using AdsManagerService.Domain.SeedWork;
using AdsManagerService.Infrastructure;
using MediatR;
using Microsoft.Extensions.Logging;

namespace AdsManagerService.API.Application.Commands;

/// <summary>
/// EN: Handler for submitting ad for review.
/// VI: Handler gửi quảng cáo để duyệt.
/// </summary>
public class SubmitAdForReviewCommandHandler : IRequestHandler<SubmitAdForReviewCommand, bool>
{
    private readonly IAdRepository _adRepository;
    private readonly IUnitOfWork _unitOfWork;
    private readonly ILogger<SubmitAdForReviewCommandHandler> _logger;

    public SubmitAdForReviewCommandHandler(
        IAdRepository adRepository,
        IUnitOfWork unitOfWork,
        ILogger<SubmitAdForReviewCommandHandler> logger)
    {
        _adRepository = adRepository ?? throw new ArgumentNullException(nameof(adRepository));
        _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<bool> Handle(SubmitAdForReviewCommand request, CancellationToken cancellationToken)
    {
        // EN: Get ad
        // VI: Lấy quảng cáo
        var ad = await _adRepository.GetByIdAsync(request.AdId);

        if (ad == null)
        {
            _logger.LogWarning("Ad {AdId} not found", request.AdId);
            return false;
        }

        // EN: Submit for review (domain logic handles validation)
        // VI: Gửi duyệt (domain logic xử lý validation)
        ad.SubmitForReview();

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

        _logger.LogInformation("Ad {AdId} submitted for review", request.AdId);

        return true;
    }
}
