namespace Brizco.Repository.Handlers.Complex;

public class DeleteComplexCommandHandler : IRequestHandler<DeleteComplexCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public DeleteComplexCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(DeleteComplexCommand request, CancellationToken cancellationToken)
    {
        try
        {
            await _repositoryWrapper.BeginTransaction(cancellationToken);
            var task = await _repositoryWrapper.SetRepository<Domain.Entities.Complex.Complex>()
                .TableNoTracking
                .FirstOrDefaultAsync(s => s.Id == request.Id, cancellationToken);
            if (task == null)
                throw new AppException("Task not found", ApiResultStatusCode.NotFound);
            _repositoryWrapper.SetRepository<Domain.Entities.Complex.Complex>()
                .Delete(task);

            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            await _repositoryWrapper.CommitAsync(cancellationToken);
            return true;
        }
        catch (Exception)
        {
            await _repositoryWrapper.RollBackAsync(cancellationToken);
            throw;
        }
    }
}