---
- name: Converge idrac_gather_facts for Power Supply
  hosts: all
  gather_facts: false
  vars:
    hostname: "{{ lookup('env', 'IDRAC_IP') }}"
    username: "{{ lookup('env', 'IDRAC_USER') }}"
    password: "{{ lookup('env', 'IDRAC_PASSWORD') }}"
    idrac_port: "{{ lookup('env', 'IDRAC_PORT') }}"
    validate_certs: false
    target:
      - SystemMetrics
    idrac_gather_facts_uri_method: "GET"
    idrac_gather_facts_uri_headers:
      Accept: "application/json"
      Content-Type: "application/json"
      OData-Version: "4.0"
    idrac_gather_facts_uri_body_format: "json"
    idrac_gather_facts_uri_status_code:
      - 200
      - 400
      - 401
      - 404
      - -1
    idrac_gather_facts_uri_return_content: true
    diff_data: {}
    exclude_keys: []

  tasks:

    - name: Find the chassis API
      ansible.builtin.include_tasks:
        ../../tests/asserts/_check_chassis_url.yml

    - name: Gather Facts for the System Metrics component
      ansible.builtin.include_role:
        name: "idrac_gather_facts"

    - name: Call assertion for thermal metrics
      ansible.builtin.include_tasks: ../../tests/asserts/tmetrics_assert.yml

    - name: Call assertion for memory metrics
      ansible.builtin.include_tasks: ../../tests/asserts/mmetrics_assert.yml

    - name: Get Power Supply information.
      ansible.builtin.uri:
        url: "https://{{ hostname }}{{ api_chassis }}/PowerSubsystem/PowerSupplies?$expand=*($levels=1)"
        validate_certs: "{{ validate_certs }}"
        method: "{{ idrac_gather_facts_uri_method }}"
        user: "{{ username }}"
        password: "{{ password }}"
        headers: "{{ idrac_gather_facts_uri_headers }}"
        body_format: "{{ idrac_gather_facts_uri_body_format }}"
        status_code: "{{ idrac_gather_facts_uri_status_code }}"
        return_content: "{{ idrac_gather_facts_uri_return_content }}"
      register: response_power_supply
      ignore_errors: true
      no_log: false

    - name: Get Power Supply Metrics ids
      ansible.builtin.set_fact:
        psu_ids: "{{ power_result.json.Members | map(attribute='Id') | list }}"
      when: power_result.status == 200

    - name: Assert Power Supply Metrics metrics
      ansible.builtin.assert:
        that:
          - "((psu_ids | length == 0) and (power_metrics | length == 0))"
        fail_msg: "The response from the role does not match"
        success_msg: "The response from the role matches"
      when: psu_ids is defined and psu_ids | length == 0

    - name: Call assertion for Power metrics
      ansible.builtin.include_tasks: ../../tests/asserts/psmetrics_assert.yml
      with_items: "{{ power_metrics }}"
      loop_control:
        loop_var: power_data
        index_var: index
      when: power_result.status == 200 and psu_ids | length > 0
