using AdsManagerService.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AdsManagerService.API.Application.Queries;

/// <summary>
/// EN: Handler for getting ad by ID.
/// VI: Handler lấy quảng cáo theo ID.
/// </summary>
public class GetAdByIdQueryHandler : IRequestHandler<GetAdByIdQuery, AdDto?>
{
    private readonly AdsManagerServiceContext _context;

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

    public async Task<AdDto?> Handle(GetAdByIdQuery request, CancellationToken cancellationToken)
    {
        var ad = await _context.Ads
            .Where(a => a.Id == request.AdId)
            .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
            })
            .FirstOrDefaultAsync(cancellationToken);

        return ad;
    }
}
