---
- name: Validate deleting a user
  hosts: all
  gather_facts: false
  vars:
    idrac_user_name: "moleculeTest"
  tasks:
    - name: Delete iDRAC user
      ansible.builtin.import_role:
        name: idrac_user
      vars:
        hostname: "{{ lookup('env', 'IDRAC_IP') }}"
        username: "{{ lookup('env', 'IDRAC_USER') }}"
        password: "{{ lookup('env', 'IDRAC_PASSWORD') }}"
        validate_certs: false
        state: absent
        user_name: "{{ idrac_user_name }}"

    - name: Asserting user deletion in check mode
      ansible.builtin.assert:
        that: idrac_user_out.msg == "Changes found to commit!"
      when: ansible_check_mode
      tags: molecule-idempotence-notest

    - name: Fetching user info in normal mode
      ansible.builtin.include_tasks:
        file: ../resources/idrac_user/get_user_info.yml
      vars:
        idrac_user_name: "{{ default(omit) }}"
      when: not ansible_check_mode and idrac_user_out.changed
      tags: molecule-idempotence-notest

    - name: Extracting username
      ansible.builtin.set_fact:
        user_list: "{{ user_details.user_info | map(attribute='UserName') }}"
      when: not ansible_check_mode and idrac_user_out.changed
      tags: molecule-idempotence-notest

    - name: Asserting user deletion in normal mode
      ansible.builtin.assert:
        that:
          - idrac_user_out.msg == "Successfully deleted user account."
          - "{{ idrac_user_name not in user_list }}"
      when: not ansible_check_mode and idrac_user_out.changed
      tags: molecule-idempotence-notest

    - name: Asserting user deletion in idempotency mode
      ansible.builtin.assert:
        that:
          - idrac_user_out.msg == "The user account is absent."
      when: not ansible_check_mode and not idrac_user_out.changed
