---

- name: "Reading users by username <{{ current_user_id }}> from realm <{{ management_oidc_realm }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ shared_service_url_keycloak }}/auth/admin/realms/{{ management_oidc_realm }}/users?username={{ current_user_id }}"
    method: GET
    headers:
      Authorization: "Bearer {{ access_token }} "
    status_code: [200]
  register: keycloak_user_result

- name: "Reading user id for username <{{ current_user_id }}>"
  set_fact:
    keycloak_user_id: "{{ keycloak_user_result.json | json_query(querystr1) | first }}"
  vars:
    querystr1: "[*].id"

- name: "Reading user attibutes for username <{{ current_user_id }}>"
  set_fact:
    keycloak_user_attributes: "{{ keycloak_user_result.json | json_query(querystr1) | first | default([]) }}"
  vars:
    querystr1: "[*].attributes"

- name: "Calculate assigned tenant ids for username <{{ current_user_id }}>"
  set_fact:
    user_tenant_ids: "\
      {% set  list= [] %}\
      {% for tenant in pmci_tenants_results.json %}\
        {% for user in tenant.user_ids %}\
          {% if user == current_user_id %}\
            {{ list.append(tenant.key) }}\
          {% endif %}\
        {% endfor %}\
      {% endfor %}\
      {{ list | list | unique | sort }}"

- name: "Calculate assigned tenant ids for username <{{ current_user_id }}>"
  set_fact:
    keycloak_user_attributes_tenant_ids:
      tenantIds: "{{ (['###'] + user_tenant_ids) | join(',') }}"

- name: "Calculate assigned tenant ids for username <{{ current_user_id }}>"
  set_fact:
    keycloak_user_attributes: "{{ keycloak_user_attributes | combine( keycloak_user_attributes_tenant_ids ) }}"

- name: "Updating user attributes for username <{{ current_user_id }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ shared_service_url_keycloak }}/auth/admin/realms/{{ management_oidc_realm }}/users/{{ keycloak_user_id }}"
    method: PUT
    body_format: json
    body: '{"attributes": {{ keycloak_user_attributes }}}'
    headers:
      Content-Type: "application/json"
      Authorization: "Bearer {{ access_token }}"
    status_code: [204]
