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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.UpdateDiscountProduct;

public class UpdateDiscountProductCommandHandler : IRequestHandler<UpdateDiscountProductCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(UpdateDiscountProductCommand request, CancellationToken cancellationToken)
    {
        var product = await _context.DiscountProducts
            .FirstOrDefaultAsync(p => p.Id == request.ProductId, cancellationToken);

        if (product == null)
            throw new Exception("محصول یافت نشد");

        product.Title = request.Title;
        product.ShortInfomation = request.ShortInfomation;
        product.FullInformation = request.FullInformation;
        product.Price = request.Price;
        product.MaxDiscountPercent = request.MaxDiscountPercent;
        product.ImagePath = request.ImagePath;
        product.ThumbnailPath = request.ThumbnailPath;
        product.RemainingCount = request.RemainingCount;
        product.IsActive = request.IsActive;

        // Update categories
        var existingCategories = await _context.DiscountProductCategories
            .Where(pc => pc.ProductId == request.ProductId)
            .ToListAsync(cancellationToken);

        _context.DiscountProductCategories.RemoveRange(existingCategories);

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

            _context.DiscountProductCategories.AddRange(newCategories);
        }

        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
