---
- name: "GETTING all clients for realm <{{ realm_name }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ shared_service_url_keycloak }}/auth/admin/realms/{{ realm_name }}/clients"
    method: GET
    headers:
      Authorization: "Bearer {{ bearer_token }} "
    status_code: [200]
  register: get_all_clients

- name: "CREATING client <{{ client_id }}> for realm <{{ realm_name }}>"
  uri:
    url: "{{ shared_service_url_keycloak }}/auth/admin/realms/{{ realm_name }}/clients"
    method: POST
    body_format: json
    body: "{{ keycloak_client_object }}"
    headers:
      Authorization: "Bearer {{ bearer_token }} "
    status_code: [201]
  changed_when: True
  when:
    - get_all_clients.json | selectattr('clientId', 'equalto', client_id) | list | length == 0
  delegate_to: 127.0.0.1
  become: false

- name: "Extract client_id from all_clients"
  set_fact:
    id: '{{ ( get_all_clients.json | selectattr("clientId","equalto",client_id) | first ).id }}'
  when: 
  - get_all_clients.json | selectattr('clientId', 'equalto', client_id) | list | length == 1

- name: "UPDATING client <{{ client_id }}> for realm <{{ realm_name }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: '{{ shared_service_url_keycloak }}/auth/admin/realms/{{ realm_name }}/clients/{{ id }}'
    method: PUT
    body_format: json
    body: "{{ keycloak_client_object }}"
    headers:
      Authorization: "Bearer {{ bearer_token }} "
    status_code: [204]
  changed_when: True
  when: 
  - get_all_clients.json | selectattr('clientId', 'equalto', client_id) | list | length == 1

- name: "DELETING client <{{ client_id }}> for realm <{{ realm_name }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: '{{ shared_service_url_keycloak }}/auth/admin/realms/{{ realm_name }}/clients/{{ id }}'
    method: DELETE
    body_format: json
    body: "{{ keycloak_client_object }}"
    headers:
      Authorization: "Bearer {{ bearer_token }} "
    status_code: [204]
  changed_when: True
  when: 
  - get_all_clients.json | selectattr('clientId', 'equalto', client_id) | list | length == 1
  - remove_client | default(False) | bool
