using Microsoft.EntityFrameworkCore;

namespace Netina.Repository.Handlers.ProductCategories;

public class DeleteProductCategoryCommandHandler : IRequestHandler<DeleteProductCategoryCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public DeleteProductCategoryCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(DeleteProductCategoryCommand request, CancellationToken cancellationToken)
    {

        var ent = await _repositoryWrapper.SetRepository<ProductCategory>().TableNoTracking
            .FirstOrDefaultAsync(c => c.Id == request.Id, cancellationToken);
        if (ent == null)
            throw new AppException("ProductCategory not found", ApiResultStatusCode.NotFound);
        _repositoryWrapper.SetRepository<ProductCategory>().Delete(ent);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}