public async Task <PCMSAPIResponse <bool> > MoveAttachments(
            [FromBody] APIRequest <int> request
            )
        {
            CheckAuthentication(request);
            var connection = await ConnectionCreate(request);

            var folderKey            = $"Defendant:{request.Context.DefendantID}";
            var folderKeyDestination = $"Defendant:{request.Parameters}";

            var config = CountyState.Read(request.Context.CountyState);

            // ensure everything exists before we try this
            var sourceFolderIdentifier      = new FolderIdentifier(config.UserIdentifier.OrganizationKey, folderKey);
            var destinationFolderIdentifier = new FolderIdentifier(config.UserIdentifier.OrganizationKey, folderKeyDestination);

            var folder = await connection.Folder.GetAsync(sourceFolderIdentifier)
                         ?? await connection.Folder.PutAsync(new FolderModel(sourceFolderIdentifier));

            var folderDestination = await connection.Folder.GetAsync(destinationFolderIdentifier)
                                    ?? await connection.Folder.PutAsync(new FolderModel(destinationFolderIdentifier));

            folder = await connection.Folder.GetAsync(sourceFolderIdentifier, new List <PopulationDirective>
            {
                new PopulationDirective(nameof(FolderModel.Files))
            });

            if (folder != null)
            {
                foreach (var file in folder.Files.Rows)
                {
                    await connection.ConcurrencyRetryBlock(async() =>
                    {
                        var updateFile = await connection.File.GetAsync(file.Identifier);
                        var views      = updateFile.Read <List <AlternativeView> >(MetadataKeyConstants.ALTERNATIVE_VIEWS);
                        if (views != null)
                        {
                            foreach (var view in views)
                            {
                                if (view.FileIdentifier.FolderKey == folder.Identifier.FolderKey)
                                {
                                    view.FileIdentifier.FolderKey = folderDestination.Identifier.FolderKey;
                                }
                            }
                            updateFile.Write(MetadataKeyConstants.ALTERNATIVE_VIEWS, views);
                        }

                        var childOf = updateFile.Read <FileIdentifier>(MetadataKeyConstants.CHILDOF);
                        if (childOf != null)
                        {
                            if (childOf.FolderKey == childOf.FolderKey)
                            {
                                childOf.FolderKey = childOf.FolderKey;
                            }
                            updateFile.Write(MetadataKeyConstants.CHILDOF, childOf);
                        }

                        if (views != null || childOf != null)
                        {
                            await connection.File.PutAsync(updateFile);
                        }
                    });

                    await connection.File.MoveAsync(
                        new FileIdentifier(destinationFolderIdentifier, file.Identifier.FileKey),
                        file.Identifier
                        );
                }
            }

            return(new PCMSAPIResponse <bool>
            {
                Response = true
            });
        }
        private async Task <Connection> ConnectionCreate(APIRequest request)
        {
            try
            {
                Logger.LogInformation($"Connection Create {JsonConvert.SerializeObject(request?.Context)}");
                Logger.LogDebug(request.Context.CountyState);

                var config = CountyState.Read(request.Context.CountyState);

                var connection = new Connection(new Uri(Configuration.APIUrl))
                {
                    Logger = Logger
                };
                bool needToken = true;

                if (request.Context.UserState != null)
                {
                    Logger.LogDebug($"Reusing existing token");
                    connection.Token = request.Context.UserState;

                    needToken = !(await connection.HealthGetAsync());
                    Logger.LogDebug($"NeedNewToken: {needToken}");
                }

                if (needToken)
                {
                    var tokenResponse = await connection.User.AuthenticateAsync(new TokenRequestModel
                    {
                        Identifier = config.UserIdentifier,
                        Password   = config.UserSecret
                    });

                    var userIdentifier = new UserIdentifier
                    {
                        OrganizationKey = config.UserIdentifier.OrganizationKey,
                        UserKey         = request.Context.EmailAddress
                    };

                    await connection.ConcurrencyRetryBlock(async() =>
                    {
                        var user = await connection.User.GetAsync(userIdentifier);
                        if (user == null)
                        {
                            user = new UserModel(userIdentifier)
                            {
                                EmailAddress = request.Context.EmailAddress
                            };

                            user = await connection.User.PutAsync(user);
                        }

                        var identifiers = user.UserAccessIdentifiers?.ToList() ?? new List <string>();

                        bool dirty = false;

                        dirty = EnsureExists(identifiers, $"o:{user.Identifier.OrganizationKey}") || dirty;
                        dirty = EnsureExists(identifiers, $"x:eDiscovery") || dirty;

                        if (dirty)
                        {
                            await connection.User.AccessIdentifiersPutAsync(user.Identifier, identifiers);
                        }
                    });

                    tokenResponse = await connection.User.ImpersonateAsync(userIdentifier);

                    Logger.LogDebug($"Acquired new token: {connection.Token}");
                }

                userState = connection.Token;

                return(connection);
            }
            catch (Exception e)
            {
                Logger.LogError(0, e, "Failed to login");
                throw;
            }
        }
        public async Task <PCMSAPIResponse <bool> > EDiscoveryStatisticsAsync([FromBody] APIRequest request)
        {
            CheckAuthentication(request);
            var connection = await ConnectionCreate(request);

            var config = CountyState.Read(request.Context.CountyState);

            var folderKey        = $"Defendant:{request.Context.DefendantID}";
            var folderIdentifier = new FolderIdentifier(config.UserIdentifier.OrganizationKey, folderKey);

            var stats = new EDiscoveryStatisticsResponse();

            // Setup our state so we have everything we need.
            var folder = await connection.Folder.GetAsync(folderIdentifier, new List <PopulationDirective>
            {
                new PopulationDirective
                {
                    Name = nameof(FolderModel.Files)
                }
            });

            if (folder?.Files?.Rows != null)
            {
                foreach (var file in folder.Files.Rows.ToList())
                {
                    switch (GetCurrentShareState(file))
                    {
                    case EDiscoveryShareState.NotShared:
                        // No Op here
                        break;

                    case EDiscoveryShareState.Staged:
                        stats.FilesStaged++;
                        break;

                    case EDiscoveryShareState.Published:
                        stats.FilesPublished++;
                        break;

                    default:
                        break;
                    }
                }
            }

            if (folder != null)
            {
                // Really the thing stored at this metadata key is a EdiscoveryRecipient, but I'm hoping we can get away with just bringing it back out as an object, because we
                // only need the count off of it.
                stats.RecipientCount = folder.Read <List <object> >(MetadataKeyConstants.E_DISCOVERY_RECIPIENT_LIST, defaultValue: new List <object>()).Count();

                stats.IsEDiscoveryActive = folder.Read <bool>(MetadataKeyConstants.E_DISCOVERY_ACTIVE_METAKEY);
            }

            bool allowed = stats.FilesPublished == 0;

            return(new PCMSAPIResponse <bool>
            {
                Response = allowed
            });
        }