using AdsManagerService.API.Application.Queries;
using AdsManagerService.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AdsManagerService.API.Controllers;

/// <summary>
/// EN: Handler for listing pending ads.
/// VI: Handler liệt kê quảng cáo chờ duyệt.
/// </summary>
public class ListPendingAdsQueryHandler : IRequestHandler<ListPendingAdsQuery, List<AdDto>>
{
    private readonly AdsManagerServiceContext _context;

    public ListPendingAdsQueryHandler(AdsManagerServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<List<AdDto>> Handle(ListPendingAdsQuery request, CancellationToken cancellationToken)
    {
        var ads = await _context.Ads
            .Where(a => a.ReviewStatus.Name == "Pending")
            .OrderBy(a => a.CreatedAt)
            .Skip((request.Page - 1) * request.PageSize)
            .Take(request.PageSize)
            .Select(a => new AdDto
            {
                Id = a.Id,
                AdSetId = a.AdSetId,
                Name = a.Name,
                Format = a.Format.Name,
                Status = a.Status.Name,
                ReviewStatus = a.ReviewStatus.Name,
                Headline = a.Headline,
                PrimaryText = a.PrimaryText,
                Description = a.Description,
                CallToAction = a.CallToAction,
                DestinationUrl = a.DestinationUrl,
                CreativeUrl = a.CreativeUrl,
                CreatedAt = a.CreatedAt,
                UpdatedAt = a.UpdatedAt
            })
            .ToListAsync(cancellationToken);

        return ads;
    }
}
