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

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

- name: "Extract group_id/user_id we are searching for from all available ones"
  set_fact:
    group_id: '{{ ( get_all_groups.json | selectattr("name","equalto",destination_group) | first ).id }}'
    user_id: '{{ ( get_all_users.json | selectattr("username","equalto",username) | first ).id }}'

- name: "GETTING all group for user <{{ username }}> in realm <{{ realm_name }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ keycloak_server_url }}/auth/admin/realms/{{ realm_name }}/users/{{ user_id }}/groups/"
    method: GET
    headers:
      Authorization: "Bearer {{ bearer_token }} "
    status_code: [200]
  register: get_all_groups_for_current_user

- name: "ADDING USER <{{ username }}> for realm <{{ realm_name }}> to Group <{{ destination_group }}>"
  delegate_to: 127.0.0.1
  become: false
  uri:
    url: "{{ keycloak_server_url }}/auth/admin/realms/{{ realm_name }}/users/{{ user_id }}/groups/{{ group_id }}"
    method: PUT
    body_format: json
    headers:
      Authorization: "Bearer {{ bearer_token }} "
    status_code: [204]
  changed_when: True
  when:
    - get_all_users.json | selectattr("username", "equalto", username) | list | length == 1
    - get_all_groups.json | selectattr("name", "equalto", destination_group) | list | length == 1
    - get_all_groups_for_current_user.json | selectattr("name", "equalto", destination_group) | list | length == 0 # do PUT-reqeust only if user is not member of group
