---
- name: Create WireGuard Client Configurations
  hosts: vpn
  become: true
  gather_facts: false
  
  tasks:
    - name: Ensure client directory exists
      file:
        path: /etc/wireguard/clients
        state: directory
        mode: '0700'
    
    - name: Load existing server keys
      slurp:
        src: /etc/wireguard/server-public.key
      register: server_pub_key
    
    - name: Set server public key fact
      set_fact:
        wg_server_public_key: "{{ server_pub_key.content | b64decode | trim }}"
    
    - name: Generate client configurations
      include_role:
        name: wireguard
        tasks_from: configure
      vars:
        wg_server_public_key: "{{ server_pub_key.content | b64decode | trim }}"
    
    - name: List created client configurations
      find:
        paths: /etc/wireguard/clients
        patterns: "*.conf"
      register: client_configs
    
    - name: Show created configurations
      debug:
        msg: "Created client configurations: {{ client_configs.files | map(attribute='path') | map('basename') | list }}"
    
    - name: Generate QR codes for mobile clients
      shell: qrencode -t ansiutf8 < /etc/wireguard/clients/{{ item.name }}.conf
      loop: "{{ wireguard_clients }}"
      register: qr_results
      when: item.name is search('phone|mobile')
      ignore_errors: true
    
    - name: Display QR codes
      debug:
        msg: |
          QR Code for {{ item.item.name }}:
          {{ item.stdout }}
      loop: "{{ qr_results.results }}"
      when: item.stdout is defined and not item.failed
