using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Orders;

namespace Netina.Repository.Handlers.Orders;

public class DeleteOrderCommandHandler : IRequestHandler<DeleteOrderCommand,bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public DeleteOrderCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(DeleteOrderCommand request, CancellationToken cancellationToken)
    {
        var order = await _repositoryWrapper.SetRepository<Order>()
            .TableNoTracking
            .FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);
        if (order == null)
            throw new AppException("Order not found", ApiResultStatusCode.NotFound);
        _repositoryWrapper.SetRepository<Order>().Delete(order);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}