public async Task <bool> Handle(UpdateOrganisationRequest request, CancellationToken cancellationToken)
        {
            request.LegalName   = _textSanitiser.SanitiseInputText(request.LegalName);
            request.TradingName = _textSanitiser.SanitiseInputText(request.TradingName);

            var command = new UpdateOrganisationCommand
            {
                OrganisationId            = request.OrganisationId,
                OrganisationTypeId        = request.OrganisationTypeId,
                ApplicationDeterminedDate = request.ApplicationDeterminedDate,
                CharityNumber             = request.CharityNumber,
                CompanyNumber             = request.CompanyNumber,
                LegalName      = request.LegalName,
                ProviderTypeId = request.ProviderTypeId,
                TradingName    = request.TradingName,
                Username       = request.Username
            };

            _logger.LogInformation($@"Handling Update organisation for Organisation ID [{request.OrganisationId}]");

            var errorMessage = _organisationValidator.ValidateOrganisation(command);

            if (!string.IsNullOrEmpty(errorMessage?.Message))
            {
                _logger.LogInformation($@"Update organisation for Organisation ID [{request.OrganisationId}] failed validation because {errorMessage.Message}");
                throw new BadRequestException(errorMessage.Message);
            }

            var auditChanges = _auditLogService.AuditOrganisation(command);

            if (auditChanges is null)
            {
                _logger.LogInformation($@"Update organisation for Organisation ID [{request.OrganisationId}] not applied as no differences found");
                return(true);
            }

            var success = await _updateOrganisationRepository.UpdateOrganisation(command);

            if (!success)
            {
                _logger.LogInformation($@"Update organisation for Organisation ID [{request.OrganisationId}] not applied as no update made on an existing record");
                return(false);
            }

            var fieldsAuditWritten = await _updateOrganisationRepository.WriteFieldChangesToAuditLog(auditChanges);

            if (!fieldsAuditWritten)
            {
                _logger.LogInformation($@"Update organisation  audit for Organisation ID [{request.OrganisationId}] not applied as no insertion made on Audit table");
                return(await Task.FromResult(false));
            }



            return(true);
        }
        public async Task <bool> Handle(UpdateOrganisationLegalNameRequest request, CancellationToken cancellationToken)
        {
            var legalName = _textSanitiser.SanitiseInputText(request.LegalName);

            if (!_validator.IsValidLegalName(legalName))
            {
                string invalidLegalNameError = $@"Invalid Organisation Legal Name '{legalName}'";
                _logger.LogInformation(invalidLegalNameError);
                throw new BadRequestException(invalidLegalNameError);
            }

            _logger.LogInformation($@"Handling Update '{FieldChanged}' for Organisation ID [{request.OrganisationId}]");

            var auditRecord = _auditLogService.AuditLegalName(request.OrganisationId, request.UpdatedBy, legalName);

            if (!auditRecord.ChangesMade)
            {
                return(await Task.FromResult(false));
            }

            var success = await _updateOrganisationRepository.UpdateLegalName(request.OrganisationId, legalName, request.UpdatedBy);

            if (!success)
            {
                return(await Task.FromResult(false));
            }

            return(await _updateOrganisationRepository.WriteFieldChangesToAuditLog(auditRecord));
        }
        public Task <Guid?> Handle(CreateOrganisationRequest request, CancellationToken cancellationToken)
        {
            request.LegalName   = _textSanitiser.SanitiseInputText(request.LegalName);
            request.TradingName = _textSanitiser.SanitiseInputText(request.TradingName);

            if (!IsValidCreateOrganisation(request))
            {
                string invalidOrganisationError = $@"Invalid Organisation data";
                if (!_organisationValidator.IsValidLegalName(request.LegalName))
                {
                    invalidOrganisationError = $"{invalidOrganisationError}: Invalid Legal Name [{request.LegalName}]";
                }

                if (!_organisationValidator.IsValidTradingName(request.TradingName))
                {
                    invalidOrganisationError = $"{invalidOrganisationError}: Invalid Trading Name [{request.TradingName}]";
                }

                if (!_providerTypeValidator.IsValidProviderTypeId(request.ProviderTypeId))
                {
                    invalidOrganisationError = $"{invalidOrganisationError}: Invalid Provider Type Id [{request.ProviderTypeId}]";
                }

                if (!_organisationValidator.IsValidOrganisationTypeId(request.OrganisationTypeId))
                {
                    invalidOrganisationError = $"{invalidOrganisationError}: Invalid Organisation Type Id [{request.OrganisationTypeId}]";
                }

                if (!_organisationValidator.IsValidStatusDate(request.StatusDate))
                {
                    invalidOrganisationError = $"{invalidOrganisationError}: Invalid Status Date [{request.StatusDate}]";
                }

                if (!_organisationValidator.IsValidUKPRN(request.Ukprn))
                {
                    invalidOrganisationError = $"{invalidOrganisationError}: Invalid ukprn [{request.Ukprn}]";
                }

                var duplicateUkrnDetails = _organisationValidator.DuplicateUkprnInAnotherOrganisation(request.Ukprn, Guid.NewGuid());

                if (duplicateUkrnDetails.DuplicateFound)
                {
                    invalidOrganisationError = $"{invalidOrganisationError}: Duplicate ukprn '{request.Ukprn}' already exists against [{duplicateUkrnDetails.DuplicateOrganisationName}]";
                }


                if (!_organisationValidator.IsValidCompanyNumber(request.CompanyNumber))
                {
                    invalidOrganisationError = $"{invalidOrganisationError}: Invalid company number [{request.CompanyNumber}]";
                }

                if (!_organisationValidator.IsValidApplicationDeterminedDate(request.ApplicationDeterminedDate))
                {
                    invalidOrganisationError = $"{invalidOrganisationError}: Invalid Application Determined Date [{request.ApplicationDeterminedDate}]";
                }

                if (!string.IsNullOrEmpty(request.CompanyNumber))
                {
                    var duplicateCompanyNumber =
                        _organisationValidator.DuplicateCompanyNumberInAnotherOrganisation(request.CompanyNumber,
                                                                                           Guid.NewGuid());

                    if (duplicateCompanyNumber.DuplicateFound)
                    {
                        invalidOrganisationError =
                            $"{invalidOrganisationError}: Duplicate company number '{request.CompanyNumber}' already exists against [{duplicateCompanyNumber.DuplicateOrganisationName}]";
                    }
                }


                if (!_organisationValidator.IsValidCharityNumber(request.CharityNumber))
                {
                    invalidOrganisationError = $"{invalidOrganisationError}: Invalid charity registration number [{request.CharityNumber}]";
                }

                if (!string.IsNullOrEmpty(request.CharityNumber))
                {
                    var duplicateCharityNumber =
                        _organisationValidator.DuplicateCharityNumberInAnotherOrganisation(request.CharityNumber,
                                                                                           Guid.NewGuid());

                    if (duplicateCharityNumber.DuplicateFound)
                    {
                        invalidOrganisationError =
                            $"{invalidOrganisationError}: Duplicate charity registration number '{request.CharityNumber}' already exists against [{duplicateCharityNumber.DuplicateOrganisationName}]";
                    }
                }

                _logger.LogInformation(invalidOrganisationError);
                throw new BadRequestException(invalidOrganisationError);
            }

            _logger.LogInformation($@"Handling Create Organisation Search for UKPRN [{request.Ukprn}]");

            var command        = _mapper.Map(request);
            var organisationId = _organisationRepository.CreateOrganisation(command);

            if (request.ProviderTypeId != ProviderType.SupportingProvider)
            {
                _eventsRepository.AddOrganisationStatusEvents(command.Ukprn, command.OrganisationStatusId,
                                                              command.StatusDate);
            }

            return(organisationId);
        }