class AccountReferenceInConsentUpdater {

    public CmsResponse<AisConsent> updateCardAccountReferences(String consentId, AisConsent aisConsent, List<Xs2aCardAccountDetails> 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(enrichCardAccountReferencesGlobal(accountDetails));
            transactions.addAll(enrichCardAccountReferencesGlobal(accountDetails));
            balances.addAll(enrichCardAccountReferencesGlobal(accountDetails));
        } else {
            for (Xs2aCardAccountDetails accountDetail : accountDetails) {
                accounts.addAll(enrichCardAccountReferences(accountDetail, existingAccess.getAccounts()));
                balances.addAll(enrichCardAccountReferences(accountDetail, existingAccess.getBalances()));
                transactions.addAll(enrichCardAccountReferences(accountDetail, existingAccess.getTransactions()));
            }
        }

        for (Xs2aCardAccountDetails accountDetail : accountDetails) {
            if (additionalInformationAccess != null && additionalInformationAccess.getOwnerName() != null) {
                ownerName.addAll(enrichCardAccountReferences(accountDetail, additionalInformationAccess.getOwnerName()));
            }
            if (additionalInformationAccess != null && additionalInformationAccess.getTrustedBeneficiaries() != null) {
                trustedBeneficiaries.addAll(enrichCardAccountReferences(accountDetail, additionalInformationAccess.getTrustedBeneficiaries()));
            }
        }

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

        return aisConsentService.updateAspspAccountAccess(consentId, accountAccess);
    }

}