---
- name: Run query to check if repuser was created correctly
  ansible.builtin.include_role:
    name: manage_dbserver
    tasks_from: execute_sql_query
    apply:
      delegate_to: "{{ primary_inventory_hostname }}"
      run_once: true
  vars:
    pg_query:
      - query: "select * from pg_user where usename = 'repuser' and userepl = 't'"
        db: "{{ pg_database }}"

- name: Set repuser_query_result with sql_query_output
  ansible.builtin.set_fact:
    repuser_query_result: "{{ sql_query_output }}"
  become: true

- name: Check if repuser was created correctly
  ansible.builtin.assert:
    that:
      - repuser_query_result.results[0].query_result[0]['usename'] == 'repuser'
      - repuser_query_result.results[0].query_result[0]['userepl']|bool
    fail_msg: "repuser was not succesfully created"
    success_msg: "repuser was succesfully created"
  run_once: true

- name: Get the standby nodes information
  ansible.builtin.set_fact:
    standby_node_info: "{{ pg_cluster_nodes | selectattr('node_type', 'equalto', 'standby') | default([]) | list }}"

- name: Run query to check if pg_stat_replication gives correct results
  ansible.builtin.include_role:
    name: manage_dbserver
    tasks_from: execute_sql_query
    apply:
      delegate_to: "{{ primary_inventory_hostname }}"
      run_once: true
  vars:
    pg_query:
      - query: "select application_name from pg_stat_replication"
        db: "{{ pg_database }}"

- name: Set pg_stat_query_result with sql_query_output
  ansible.builtin.set_fact:
    pg_stat_query_result: "{{ sql_query_output }}"
  become: true

- name: Check if pg_stat_replication gives correct results
  ansible.builtin.assert:
    that:
      - pg_stat_query_result.results[0].query_result|length == standby_node_info|length
    fail_msg: "Not enough replication connections established"
    success_msg: "Enough replication connections established"
  run_once: true

- name: Run query to check replication status on standby nodes
  ansible.builtin.include_role:
    name: manage_dbserver
    tasks_from: execute_sql_query
  vars:
    pg_query:
      - query: "select status from pg_stat_wal_receiver"
        db: "{{ pg_database }}"
  when:
    - "'standby' in group_names"

- name: Set pg_wal_reciever_query_result with sql_query_output
  ansible.builtin.set_fact:
    pg_wal_reciever_query_result: "{{ sql_query_output }}"
  become: true
  when:
    - "'standby' in group_names"

- name: Check if replication was successful on standby nodes
  ansible.builtin.assert:
    that:
      - pg_wal_reciever_query_result.results[0].query_result[0]['status'] == 'streaming'
    fail_msg: "Replication was not successful on standby nodes"
    success_msg: "Replication was successful on standby nodes"

- name: Reset variables
  ansible.builtin.set_fact:
    repuser_query_result: null
    pg_stat_query_result: null
    pg_wal_reciever_query_result: null
    standby_node_info: null
