---
# PHP Webapp Deployment (Handle missing PHP config files)

- name: Create app directory
  file:
    path: "{{ app_directory }}"
    state: directory
    mode: '0755'

- name: Check if docker-compose.yml exists locally first
  local_action:
    module: stat
    path: "{{ local_app_path }}/docker-compose.yml"
  register: local_compose_exists
  become: no

- name: Show local docker-compose.yml status
  debug:
    msg: |
      🔍 Local docker-compose.yml check:
      - Path: {{ local_app_path }}/docker-compose.yml
      - Exists: {{ local_compose_exists.stat.exists }}

- name: Fail if docker-compose.yml doesn't exist locally
  fail:
    msg: |
      ❌ docker-compose.yml nicht im lokalen Projekt gefunden!

      Geprüft: {{ local_app_path }}/docker-compose.yml

      Bitte stelle sicher, dass eine docker-compose.yml in deinem Projekt-Root existiert.
  when: not local_compose_exists.stat.exists

- name: Upload project files with working synchronize
  synchronize:
    src: "{{ local_app_path }}/"
    dest: "{{ app_directory }}/"
    delete: no
    archive: yes
    checksum: yes
    rsync_opts:
      - "--exclude=ansible"
      - "--exclude=.git"
      - "--exclude=vendor"
      - "--exclude=node_modules"
      - "--exclude=storage/logs"
      - "--exclude=cache"
      - "--exclude=logs"
      - "--exclude=dist"
      - "--exclude=.archive"
      - "--exclude=x_ansible"
      - "--verbose"
  register: sync_result

- name: Check if required PHP config files exist
  stat:
    path: "{{ app_directory }}/docker/php/php.production.ini"
  register: php_prod_config

- name: Create missing PHP production config if needed
  copy:
    content: |
      ; PHP Production Configuration
      memory_limit = 256M
      upload_max_filesize = 50M
      post_max_size = 50M
      max_execution_time = 300
      max_input_vars = 3000

      ; Error reporting for production
      display_errors = Off
      log_errors = On
      error_log = /var/log/php_errors.log

      ; Opcache settings
      opcache.enable = 1
      opcache.memory_consumption = 128
      opcache.max_accelerated_files = 4000
      opcache.revalidate_freq = 2
      opcache.validate_timestamps = 0
    dest: "{{ app_directory }}/docker/php/php.production.ini"
    mode: '0644'
  when: not php_prod_config.stat.exists

- name: Check if common PHP config exists
  stat:
    path: "{{ app_directory }}/docker/php/php.common.ini"
  register: php_common_config

- name: Create missing PHP common config if needed
  copy:
    content: |
      ; PHP Common Configuration
      date.timezone = Europe/Berlin
      short_open_tag = Off
      expose_php = Off

      ; Security
      allow_url_fopen = On
      allow_url_include = Off
    dest: "{{ app_directory }}/docker/php/php.common.ini"
    mode: '0644'
  when: not php_common_config.stat.exists

- name: Ensure PHP config directory exists
  file:
    path: "{{ app_directory }}/docker/php"
    state: directory
    mode: '0755'

- name: Show what files were synced
  debug:
    msg: |
      📂 Sync Result:
      - Changed: {{ sync_result.changed }}

- name: Ensure proper permissions for directories
  file:
    path: "{{ item }}"
    state: directory
    mode: '0755'
    recurse: yes
  loop:
    - "{{ app_directory }}/public"
    - "{{ app_directory }}/src"
    - "{{ app_directory }}/docker"
  ignore_errors: yes

- name: Create storage directories if they don't exist
  file:
    path: "{{ app_directory }}/{{ item }}"
    state: directory
    mode: '0777'
  loop:
    - "storage/logs"
    - "storage/cache"
    - "cache"
    - "logs"
  ignore_errors: yes

- name: Check if docker-compose.yml exists in project root
  stat:
    path: "{{ app_directory }}/docker-compose.yml"
  register: compose_exists

- name: Check if docker-compose.yml exists in docker folder
  stat:
    path: "{{ app_directory }}/docker/docker-compose.yml"
  register: compose_docker_exists

- name: Use docker-compose.yml from docker folder if available
  copy:
    src: "{{ app_directory }}/docker/docker-compose.yml"
    dest: "{{ app_directory }}/docker-compose.yml"
    remote_src: yes
  when: compose_docker_exists.stat.exists and not compose_exists.stat.exists

- name: Manually copy docker-compose.yml if sync failed
  copy:
    src: "{{ local_app_path }}/docker-compose.yml"
    dest: "{{ app_directory }}/docker-compose.yml"
    mode: '0644'
  when: local_compose_exists.stat.exists and not compose_exists.stat.exists

- name: Show which docker-compose.yml we found
  debug:
    msg: |
      📋 Docker Compose Status:
      - Root compose exists: {{ compose_exists.stat.exists }}
      - Docker folder compose exists: {{ compose_docker_exists.stat.exists }}

- name: Fail if no docker-compose.yml found
  fail:
    msg: |
      ❌ Keine docker-compose.yml gefunden!

      Erwartet in:
      - {{ app_directory }}/docker-compose.yml
      - {{ app_directory }}/docker/docker-compose.yml

      Bitte erstelle eine docker-compose.yml in deinem Projekt.
  when: not compose_exists.stat.exists and not compose_docker_exists.stat.exists

- name: Check if public/index.php exists after sync
  stat:
    path: "{{ app_directory }}/public/index.php"
  register: index_exists

- name: Fail if index.php not found
  fail:
    msg: |
      ❌ index.php nicht gefunden!

      Geprüft: {{ app_directory }}/public/index.php

      Die Dateien wurden nicht korrekt übertragen.
  when: not index_exists.stat.exists

- name: Create environment file
  template:
    src: app.env.j2
    dest: "{{ app_directory }}/.env"
  register: env_result

- name: Check which docker compose command is available
  shell: |
    if docker compose version >/dev/null 2>&1; then
      echo "docker compose"
    elif docker-compose --version >/dev/null 2>&1; then
      echo "docker-compose"
    else
      echo "none"
    fi
  register: docker_compose_cmd
  changed_when: false

- name: Stop existing containers (if any)
  shell: "cd {{ app_directory }} && {{ docker_compose_cmd.stdout }} down"
  when: docker_compose_cmd.stdout != "none"
  ignore_errors: yes

- name: Start containers with your docker-compose.yml
  shell: "cd {{ app_directory }} && {{ docker_compose_cmd.stdout }} up -d --build"
  register: start_result
  when: docker_compose_cmd.stdout != "none"

- name: Wait for application to start
  wait_for:
    port: "{{ app_port }}"
    host: "127.0.0.1"
    delay: 5
    timeout: 60

- name: Test if app is accessible
  uri:
    url: "http://127.0.0.1:{{ app_port }}/"
    method: GET
    status_code: [200, 301, 302]
  register: app_test
  ignore_errors: yes

- name: Show container status
  shell: "cd {{ app_directory }} && {{ docker_compose_cmd.stdout }} ps"
  register: container_status
  when: docker_compose_cmd.stdout != "none"
  ignore_errors: yes

- name: Show deployment result
  debug:
    msg: |
      🎉 Projekt {{ app_name }} erfolgreich deployed!

      📂 Projektdateien synchronisiert von: {{ local_app_path }}
      🐳 Verwendete docker-compose.yml:
      {% if compose_exists.stat.exists %}
      ✅ Aus Projekt-Root: {{ app_directory }}/docker-compose.yml
      {% elif compose_docker_exists.stat.exists %}
      ✅ Aus docker/ Ordner: {{ app_directory }}/docker/docker-compose.yml
      {% endif %}
      🌐 Erreichbar unter: https://{{ domain }}
      ⚙️  Docker Compose: {{ docker_compose_cmd.stdout }}

      📁 index.php Status: {{ 'Gefunden ✅' if index_exists.stat.exists else 'Nicht gefunden ❌' }}

      🐳 Container Status:
      {{ container_status.stdout if container_status.stdout is defined else 'Status konnte nicht abgerufen werden' }}

      {% if app_test.status is defined and (app_test.status == 200 or app_test.status == 301 or app_test.status == 302) %}
      ✅ App reagiert erfolgreich (HTTP {{ app_test.status }})
      {% else %}
      ⚠️  App-Test fehlgeschlagen - prüfe Logs mit 'make logs'
      {% endif %}
