using CMSMicroservice.Domain.Entities;
using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.ProductsCQ.Commands.CreateNewProducts;
public class CreateNewProductsCommandHandler : IRequestHandler<CreateNewProductsCommand, CreateNewProductsResponseDto>
{
    private readonly IApplicationDbContext _context;

    public CreateNewProductsCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<CreateNewProductsResponseDto> Handle(CreateNewProductsCommand request,
        CancellationToken cancellationToken)
    {
        var entity = request.Adapt<Product>();
        await _context.Products.AddAsync(entity, cancellationToken);
        await _context.SaveChangesAsync(cancellationToken);

        // ثبت دسته‌بندی‌های محصول (در صورت ارسال)
        if (request.CategoryIds is { Count: > 0 })
        {
            var distinctCategoryIds = request.CategoryIds
                .Where(id => id > 0)
                .Distinct()
                .ToList();

            foreach (var categoryId in distinctCategoryIds)
            {
                var rel = new ProductCategory
                {
                    ProductId = entity.Id,
                    CategoryId = categoryId
                };
                await _context.ProductCategories.AddAsync(rel, cancellationToken);
            }

            await _context.SaveChangesAsync(cancellationToken);
        }

        entity.AddDomainEvent(new CreateNewProductsEvent(entity));
        return entity.Adapt<CreateNewProductsResponseDto>();
    }
}
