using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.DeleteDiscountProduct;

public class DeleteDiscountProductCommandHandler : IRequestHandler<DeleteDiscountProductCommand, bool>
{
    private readonly IApplicationDbContext _context;

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

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

        if (product == null)
        {
            return false;
        }

        // حذف رابطه‌های دسته‌بندی
        var productCategories = await _context.DiscountProductCategories
            .Where(pc => pc.ProductId == request.ProductId)
            .ToListAsync(cancellationToken);

        _context.DiscountProductCategories.RemoveRange(productCategories);

        // حذف محصول
        _context.DiscountProducts.Remove(product);
        await _context.SaveChangesAsync(cancellationToken);

        return true;
    }
}
