- name: UFW Firewall Configuration
  block:
    - name: Ensure UFW is installed
      ansible.builtin.apt:
        name: ufw
        state: present

    - name: Reset UFW to defaults
      community.general.ufw:
        state: reset

    - name: Set UFW default incoming policy to deny
      community.general.ufw:
        direction: incoming
        policy: deny

    - name: Set UFW default outgoing policy to allow
      community.general.ufw:
        direction: outgoing
        policy: allow

    - name: Set UFW default forward policy to deny
      community.general.ufw:
        direction: routed
        policy: deny

    - name: Limit SSH connections on port {{ ssh_port }}
      community.general.ufw:
        rule: limit
        port: "{{ ssh_port }}"
        proto: tcp
        comment: "SSH rate limiting"

    - name: Allow incoming HTTP connections (port 80)
      community.general.ufw:
        rule: allow
        port: 80
        proto: tcp
        comment: "HTTP"

    - name: Allow incoming HTTPS connections (port 443)
      community.general.ufw:
        rule: allow
        port: 443
        proto: tcp
        comment: "HTTPS"

    - name: Set UFW logging level
      community.general.ufw:
        logging: low

    # NOTE: UFW is NOT enabled here to prevent lockout during SSH port changes
    # It will be enabled by ssh role after port transition is validated
