- name: "Ensure Mailu user {{ mailu_user }}@{{ mailu_domain }} exists"
  command: >
    docker compose exec admin flask mailu {{ mailu_action }}
      {{ mailu_user }} {{ mailu_domain }} '{{ mailu_password }}'
  args:
    chdir: "{{ mailu_compose_dir }}"
  register: mailu_user_result
  failed_when: >
    mailu_user_result.rc != 0 and
    (
      "exists, not created" not in mailu_user_result.stderr and
      "Duplicate entry"   not in mailu_user_result.stderr
    )
  changed_when: mailu_user_result.rc == 0

- name: "Change password for user {{ mailu_user }}@{{ mailu_domain }}"
  command: >
    docker compose exec admin flask mailu password
      {{ mailu_user }} {{ mailu_domain }} '{{ mailu_password }}'
  args:
    chdir: "{{ mailu_compose_dir }}"

- name: "Fetch existing API tokens via curl inside admin container"
  command: >-
    docker compose exec -T admin \
      curl -s -X GET {{ mailu_api_base_url }}/token \
        -H "Authorization: Bearer {{ mailu_global_api_token }}"
  args:
    chdir: "{{ mailu_compose_dir }}"
  register: mailu_tokens_cli
  changed_when: false

- name: "Extract existing token info for {{ mailu_user }}"
  set_fact:
    mailu_user_existing_token: >-
      {{ (
           mailu_tokens_cli.stdout
           | default('[]')
           | from_json
           | selectattr('comment','equalto', mailu_user ~ " - ansible.cymais")
           | list
         ).0 | default(None) }}

- name: "Delete existing API token for {{ mailu_user }} if local token missing but remote exists"
  command: >-
    docker compose exec -T admin \
      curl -s -X DELETE {{ mailu_api_base_url }}/token/{{ mailu_user_existing_token.id }} \
        -H "Authorization: Bearer {{ mailu_global_api_token }}"
  args:
    chdir: "{{ mailu_compose_dir }}"
  when:
    - users[mailu_user].mailu_token is not defined
    - mailu_user_existing_token is not none
  register: mailu_token_delete
  changed_when: mailu_token_delete.rc == 0

- name: "Create API token for {{ mailu_user }} if no local token defined"
  command: >-
    docker compose exec -T admin \
      curl -s -X POST {{ mailu_api_base_url }}/token \
        -H "Authorization: Bearer {{ mailu_global_api_token }}" \
        -H "Content-Type: application/json" \
        -d '{{ {
              "comment": mailu_user ~ " - ansible.cymais",
              "email": users[mailu_user].email,
              "ip": mailu_token_ip
            } | to_json }}'
  args:
    chdir: "{{ mailu_compose_dir }}"
  when: users[mailu_user].mailu_token is not defined
  register: mailu_token_creation
  changed_when: mailu_token_creation.rc == 0

- name: "Set mailu_token for {{ mailu_user }} in users dict if newly created"
  set_fact:
    users: >-
      {{ users
         | combine({
             mailu_user: (
               users[mailu_user]
               | combine({
                   'mailu_token': (mailu_token_creation.stdout | from_json).token
                 })
             )
           }, recursive=True)
      }}
  when: users[mailu_user].mailu_token is not defined
