---
- name: Deploy Vue3 Frontend Application
  hosts: webservers
  vars:
    app_name: mall-vue3
    app_version: "{{ lookup('env', 'APP_VERSION') | default('latest', true) }}"
    deploy_path: /usr/share/nginx/html/mall
    nginx_config_path: /etc/nginx/sites-available
    nginx_enabled_path: /etc/nginx/sites-enabled
    backup_path: /usr/share/nginx/html/mall/backup
    dist_archive: dist-prod.tar.gz
    frontend_path: /usr/share/nginx/html/mall/frontendui

  tasks:
    - name: Compress dist-prod directory locally
      local_action:
        module: archive
        path: ../../unpackage/dist/build
        dest: ../../{{ dist_archive }}
        format: gz
      run_once: true

    - name: Create deployment directories
      ansible.builtin.file:
        path: "{{ item }}"
        state: directory
        mode: "0755"
      with_items:
        - "{{ deploy_path }}"
        - "{{ backup_path }}"
        - "{{ frontend_path }}"
      become: true

    - name: Clean target directory
      ansible.builtin.file:
        path: "{{ frontend_path }}"
        state: directory
        mode: "0755"
      become: true

    - name: Upload compressed dist files
      ansible.builtin.copy:
        src: ../../{{ dist_archive }}
        dest: "{{ deploy_path }}/{{ dist_archive }}"
        mode: "0644"
      become: true

    - name: Extract dist files
      ansible.builtin.unarchive:
        src: "{{ deploy_path }}/{{ dist_archive }}"
        dest: "{{ frontend_path }}"
        remote_src: true
      become: true

    - name: Debug - List directory contents
      ansible.builtin.shell: "ls -la {{ frontend_path }}"
      register: dir_contents
      become: true

    - name: Debug - Show directory contents
      ansible.builtin.debug:
        var: dir_contents.stdout_lines

    - name: Remove archive file
      ansible.builtin.file:
        path: "{{ deploy_path }}/{{ dist_archive }}"
        state: absent
      become: true

    - name: Set correct permissions
      ansible.builtin.file:
        path: "{{ frontend_path }}"
        state: directory
        recurse: yes
        owner: www-data
        group: www-data
        mode: "0755"
      become: true

    - name: Copy nginx configuration
      ansible.builtin.template:
        src: templates/mall.conf.j2
        dest: "{{ nginx_config_path }}/mall.conf"
        mode: "0644"
      notify: Reload nginx
      become: true

    - name: Create symlink to enable directory
      file:
        src: "{{ nginx_config_path }}/mall.conf"
        dest: "{{ nginx_enabled_path }}/mall.conf"
        state: link
        force: yes
      become: true

    - name: Ensure nginx is running
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true
      become: true

  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded
