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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.DeleteDiscountCategory;

public class DeleteDiscountCategoryCommandHandler : IRequestHandler<DeleteDiscountCategoryCommand, bool>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<bool> Handle(DeleteDiscountCategoryCommand request, CancellationToken cancellationToken)
    {
        var category = await _context.DiscountCategories
            .Include(c => c.ChildCategories)
            .Include(c => c.ProductCategories)
            .FirstOrDefaultAsync(c => c.Id == request.CategoryId, cancellationToken);

        if (category == null)
        {
            throw new Exception($"Discount category with ID {request.CategoryId} not found");
        }

        // Check if category has child categories
        if (category.ChildCategories.Any())
        {
            throw new Exception($"Cannot delete category. It has {category.ChildCategories.Count} child categories. Please delete child categories first.");
        }

        // Check if category has products
        if (category.ProductCategories.Any())
        {
            throw new Exception($"Cannot delete category. It has {category.ProductCategories.Count} products. Please move or delete products first.");
        }

        _context.DiscountCategories.Remove(category);
        await _context.SaveChangesAsync(cancellationToken);

        return true;
    }
}
