using Microsoft.EntityFrameworkCore;

namespace NetinaShop.Repository.Handlers.Products;

public class DeleteProductCommandHandler : IRequestHandler<DeleteProductCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public DeleteProductCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(DeleteProductCommand request, CancellationToken cancellationToken)
    {
        var ent = await _repositoryWrapper.SetRepository<Product>().TableNoTracking
            .FirstOrDefaultAsync(d => d.Id == request.Id, cancellationToken);
        if (ent == null)
            throw new AppException("Product NotFound", ApiResultStatusCode.NotFound);

        _repositoryWrapper.SetRepository<Product>().Delete(ent);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}