using Microsoft.EntityFrameworkCore;

namespace NetinaShop.Repository.Handlers.Discounts;

public class DeleteDiscountCommandHandler : IRequestHandler<DeleteDiscountCommand,bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

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

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