using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities.DiscountShop;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.CreateDiscountProduct;

public class CreateDiscountProductCommandHandler : IRequestHandler<CreateDiscountProductCommand, long>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<long> Handle(CreateDiscountProductCommand request, CancellationToken cancellationToken)
    {
        var product = new DiscountProduct
        {
            Title = request.Title,
            ShortInfomation = request.ShortInfomation,
            FullInformation = request.FullInformation,
            Price = request.Price,
            MaxDiscountPercent = request.MaxDiscountPercent,
            ImagePath = request.ImagePath,
            ThumbnailPath = request.ThumbnailPath,
            RemainingCount = request.RemainingCount,
            Rate = 0,
            SaleCount = 0,
            ViewCount = 0,
            IsActive = true
        };

        _context.DiscountProducts.Add(product);
        await _context.SaveChangesAsync(cancellationToken);

        // Add product categories
        if (request.CategoryIds.Any())
        {
            var productCategories = request.CategoryIds.Select(categoryId => new DiscountProductCategory
            {
                ProductId = product.Id,
                CategoryId = categoryId
            }).ToList();

            _context.DiscountProductCategories.AddRange(productCategories);
            await _context.SaveChangesAsync(cancellationToken);
        }

        return product.Id;
    }
}
