namespace Brizco.Repository.Handlers.Activity;

public class DeleteActivityCommandHandler : IRequestHandler<DeleteActivityCommand, bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

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

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