using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.ProductCategoryCQ.Commands.DeleteProductCategory;
public class DeleteProductCategoryCommandHandler : IRequestHandler<DeleteProductCategoryCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(DeleteProductCategoryCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.ProductCategories
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(ProductCategory), request.Id);
        entity.IsDeleted = true;
        _context.ProductCategories.Update(entity);
        entity.AddDomainEvent(new DeleteProductCategoryEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
