---
- name: Récupérer l'ancienne version
  ansible.builtin.shell: "dpkg-query -W -f='${Version}' {{ vhost.type }}-{{ vhost.package_name }} || echo 'N/A'"
  register: old_version
  changed_when: false

- name: Installer le package
  ansible.builtin.apt:
    name: "{{ vhost.type }}-{{ vhost.package_name }}={{ vhost.version }}"
    state: present

- name: Récupérer la nouvelle version
  ansible.builtin.shell: "dpkg-query -W -f='${Version}' {{ vhost.type }}-{{ vhost.package_name }} || echo 'N/A'"
  register: new_version
  changed_when: false

- name: Notification en cas de mise à jour
  block:
    - name: Changer le propriétaire et permissions du projet
      file:
        path: /var/www/{{ vhost.package_name }}
        state: directory
        recurse: yes
        owner: www-data
        group: www-data
        mode: '0750'

    - name: Créer le fichier de log
      file:
        path: /var/log/nginx/{{ vhost.package_name }}.log
        state: touch
        owner: www-data
        group: www-data
        mode: '0664'

    - name: Afficher l'évolution de la version
      ansible.builtin.debug:
        msg: "📦 Mise à jour du paquet {{ vhost.package_name }} de {{ old_version.stdout }} vers {{ new_version.stdout }}"

    - name: Envoyer notification Telegram
      ansible.builtin.uri:
        url: "https://api.telegram.org/bot{{ telegram_bot_token }}/sendMessage"
        method: POST
        body_format: json
        body:
          chat_id: "{{ telegram_chat_id }}"
          text: |
            📦 {{ vhost.package_name }} mis à jour !
            Ancienne version : {{ old_version.stdout }}
            Nouvelle version : {{ new_version.stdout }}
        headers:
          Content-Type: "application/json"
  when: old_version.stdout != new_version.stdout

- name: Déployer le fichier .env
  ansible.builtin.template:
    src: "{{ vhost.env_template | default('host.env.j2') }}"
    dest: "/var/www/{{ vhost.package_name }}/.env"
    owner: www-data
    group: www-data
    mode: "0640"

- name: Exécuter les commandes artisan post-déploiement
  ansible.builtin.shell: >
    runuser -u www-data --
    /usr/bin/php{{ vhost.php_version }} artisan {{ item }}
  args:
    chdir: "/var/www/{{ vhost.package_name }}"
  loop: "{{ vhost.artisan_post_deploy_commands | default([]) }}"
  loop_control:
    label: "{{ item }}"
  when: vhost.artisan_post_deploy_commands is defined
