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

namespace AdsManagerService.API.Application.Queries;

/// <summary>
/// EN: Handler for getting ad set by ID.
/// VI: Handler lấy ad set theo ID.
/// </summary>
public class GetAdSetByIdQueryHandler : IRequestHandler<GetAdSetByIdQuery, AdSetDto?>
{
    private readonly AdsManagerServiceContext _context;

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

    public async Task<AdSetDto?> Handle(GetAdSetByIdQuery request, CancellationToken cancellationToken)
    {
        var adSet = await _context.AdSets
            .Where(a => a.Id == request.AdSetId)
            .Select(a => new AdSetDto
            {
                    Id = a.Id,
                    CampaignId = a.CampaignId,
                    Name = a.Name,
                    Status = a.Status.Name,
                    DailyBudget = a.DailyBudget,
                    BidType = a.BidStrategy.Type.ToString(),
                    BidAmount = a.BidStrategy.BidAmount,
                    StartDate = a.StartDate,
                    EndDate = a.EndDate,
                    Targeting = a.Targeting != null ? new TargetingDto
                    {
                        MinAge = a.Targeting.MinAge,
                        MaxAge = a.Targeting.MaxAge,
                        Genders = a.Targeting.Genders != null ? a.Targeting.Genders.Split(',').ToList() : null,
                        Locations = a.Targeting.Locations != null ? a.Targeting.Locations.Split(',').ToList() : null,
                        Interests = a.Targeting.Interests != null ? a.Targeting.Interests.Split(',').ToList() : null
                    } : null,
                    CreatedAt = a.CreatedAt,
                    UpdatedAt = a.UpdatedAt
                })
            .FirstOrDefaultAsync(cancellationToken);

        return adSet;
    }
}
