using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.TransactionsCQ.Commands.DeleteTransactions;
public class DeleteTransactionsCommandHandler : IRequestHandler<DeleteTransactionsCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

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