class AccountReferenceInConsentUpdater {

    public CmsResponse<AisConsent> updateAccountReferences(@NotNull String consentId, @NotNull AisConsent aisConsent, @NotNull List<Xs2aAccountDetails> accountDetails) {
        List<AccountReference> accounts = new ArrayList<>();
        List<AccountReference> transactions = new ArrayList<>();
        List<AccountReference> balances = new ArrayList<>();
        List<AccountReference> ownerName = new ArrayList<>();
        List<AccountReference> trustedBeneficiaries = new ArrayList<>();
        AccountAccess existingAccess = aisConsent.getAccess();
        AdditionalInformationAccess additionalInformationAccess = existingAccess.getAdditionalInformationAccess();

        if (aisConsent.isGlobalConsent()) {
            accounts.addAll(enrichAccountReferencesGlobal(accountDetails));
            transactions.addAll(enrichAccountReferencesGlobal(accountDetails));
            balances.addAll(enrichAccountReferencesGlobal(accountDetails));
        } else {
            for (Xs2aAccountDetails accountDetail : accountDetails) {
                accounts.addAll(enrichAccountReferences(accountDetail, existingAccess.getAccounts()));
                balances.addAll(enrichAccountReferences(accountDetail, existingAccess.getBalances()));
                transactions.addAll(enrichAccountReferences(accountDetail, existingAccess.getTransactions()));
            }
        }

        for (Xs2aAccountDetails accountDetail : accountDetails) {
            if (additionalInformationAccess != null && additionalInformationAccess.getOwnerName() != null) {
                ownerName.addAll(enrichAccountReferences(accountDetail, additionalInformationAccess.getOwnerName()));
            }

            if (additionalInformationAccess != null && additionalInformationAccess.getTrustedBeneficiaries() != null) {
                trustedBeneficiaries.addAll(enrichAccountReferences(accountDetail, additionalInformationAccess.getTrustedBeneficiaries()));
            }
        }

        AccountAccess accountAccess =
            getXs2aAccountAccess(accounts, transactions, balances, ownerName, trustedBeneficiaries, additionalInformationAccess);

        return aisConsentService.updateAspspAccountAccess(consentId, accountAccess);
    }

}