---
- name: Post-deployment validation and health checks
  hosts: servers
  gather_facts: true
  become: false
  serial: "100%"

  tasks:
    - name: Verify SSH connectivity on custom port
      ansible.builtin.wait_for:
        port: "{{ security_ssh_port | default(22) }}"
        host: "{{ ansible_host | default(inventory_hostname) }}"
        timeout: 60
        delay: 5
        state: started
      tags: validation, networking

    - name: Check critical system services
      ansible.builtin.systemd:
        name: "{{ item }}"
        state: started
        enabled: true
      loop:
        - ssh
        - docker
        - fail2ban
        - nftables
      tags: validation
      ignore_errors: true

    - name: Run comprehensive system health checks
      block:
        - name: Set root mount fact
          ansible.builtin.set_fact:
            root_mount: "{{ ansible_mounts | selectattr('mount', 'equalto', '/') | list | first }}"
          tags: validation, health
        
        - name: Check load average
          ansible.builtin.shell: cat /proc/loadavg | awk '{print $1}'
          register: load_avg
          changed_when: false
        
        - name: Check Docker status
          ansible.builtin.shell:
            cmd: docker info >/dev/null 2>&1 && echo "healthy" || echo "unhealthy"
          register: docker_status
          changed_when: false
          ignore_errors: true

        - name: Display comprehensive health status
          ansible.builtin.debug:
            msg:
              - "Health check results for {{ inventory_hostname }}:"
              - "Disk usage: {{ ((root_mount.size_total - root_mount.size_available) / root_mount.size_total * 100) | round(2) }}%"
              - "Memory usage: {{ ((ansible_memtotal_mb - ansible_memfree_mb) / ansible_memtotal_mb * 100) | round(2) }}%"
              - "Load average (1m): {{ load_avg.stdout }}"
              - "Docker: {{ docker_status.stdout }}"
          tags: always, health

      tags: validation, health
