using AdsManagerService.Domain.AggregatesModel.AdAggregate;
using MediatR;

namespace AdsManagerService.API.Application.Commands;

public class CreateAdCommandHandler : IRequestHandler<CreateAdCommand, Guid>
{
    private readonly IAdRepository _adRepository;

    public CreateAdCommandHandler(IAdRepository adRepository)
    {
        _adRepository = adRepository ?? throw new ArgumentNullException(nameof(adRepository));
    }

    public async Task<Guid> Handle(CreateAdCommand request, CancellationToken cancellationToken)
    {
        // Parse ad format
        var format = request.Format.ToLower() switch
        {
            "single_image" => AdFormat.SingleImage,
            "single_video" => AdFormat.SingleVideo,
            "carousel" => AdFormat.Carousel,
            "collection" => AdFormat.Collection,
            "stories" => AdFormat.Stories,
            _ => AdFormat.SingleImage
        };

        // Create ad
        var ad = new Ad(
            adSetId: request.AdSetId,
            name: request.Name,
            format: format,
            headline: request.Headline,
            primaryText: request.PrimaryText,
            callToAction: request.CallToAction,
            destinationUrl: request.DestinationUrl,
            creativeUrl: request.CreativeUrl
        );

        _adRepository.Add(ad);
        await _adRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        return ad.Id;
    }
}
