using AdsManagerService.Domain.AggregatesModel.AdSetAggregate;
using MediatR;

namespace AdsManagerService.API.Application.Commands;

public class CreateAdSetCommandHandler : IRequestHandler<CreateAdSetCommand, Guid>
{
    private readonly IAdSetRepository _adSetRepository;

    public CreateAdSetCommandHandler(IAdSetRepository adSetRepository)
    {
        _adSetRepository = adSetRepository ?? throw new ArgumentNullException(nameof(adSetRepository));
    }

    public async Task<Guid> Handle(CreateAdSetCommand request, CancellationToken cancellationToken)
    {
        // Create targeting
        var targeting = new Targeting(
            minAge: request.MinAge,
            maxAge: request.MaxAge,
            genders: request.Genders,
            locations: request.Locations,
            interests: request.Interests
        );

        // Create bid strategy
        var bidStrategy = request.BidType.ToLower() switch
        {
            "cpc" => BidStrategy.CPC(request.BidAmount ?? 1000),
            "cpm" => BidStrategy.CPM(request.BidAmount ?? 10000),
            "ocpm" => BidStrategy.OCPM(request.BidAmount ?? 5000),
            "automatic" => BidStrategy.Automatic(),
            _ => BidStrategy.CPC(1000)
        };

        // Create ad set
        var adSet = new AdSet(
            campaignId: request.CampaignId,
            name: request.Name,
            targeting: targeting,
            bidStrategy: bidStrategy,
            dailyBudget: request.DailyBudget
        );

        _adSetRepository.Add(adSet);
        await _adSetRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        return adSet.Id;
    }
}
