namespace Brizco.Repository.Handlers.Positions;

public class CreatePositionCommandHandler : IRequestHandler<CreatePositionCommand, PositionSDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly ICurrentUserService _currentUserService;

    public CreatePositionCommandHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
    {
        _repositoryWrapper = repositoryWrapper;
        _currentUserService = currentUserService;
    }
    public async Task<PositionSDto> Handle(CreatePositionCommand request, CancellationToken cancellationToken)
    {

        if (_currentUserService.ComplexId == null)
            throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
        if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId))
            throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);

        try
        {
            await _repositoryWrapper.BeginTransaction(cancellationToken);
            var entity = Position
                .Create(request.Title,
                    request.Description,
                    complexId,
                    request.SectionId);

            request.Permissions.ForEach(f=>entity.AddPermission(f));

            _repositoryWrapper.SetRepository<Position>().Add(entity);
            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            await _repositoryWrapper.CommitAsync(cancellationToken);
            return entity.AdaptToSDto();
        }
        catch (Exception)
        {
            await _repositoryWrapper.RollBackAsync(cancellationToken);
            throw;
        }
    }
}