---
# --- Server deployment ---
- name: Deploy e-ticket to production
  hosts: production
  become: true
  vars_files:
    - vault.yml

  pre_tasks:
    - name: Enable maintenance mode
      command: make maintenance_on
      args:
        chdir: /var/www/e-ticket

    - name: Get Docker socket GID
      stat:
        path: /var/run/docker.sock
      register: docker_sock

    - name: Set docker_gid fact
      set_fact:
        docker_gid: "{{ docker_sock.stat.gid }}"

    - name: Generate analytics secret
      set_fact:
        analytics_secret: "{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=32') }}"

  tasks:
    - name: Deploy .env.local
      template:
        src: env.local.j2
        dest: /var/www/e-ticket/.env.local
        owner: bot
        group: bot
        mode: "0600"

    - name: Ensure cert directory exists
      file:
        path: /var/www/e-ticket/config/cert
        state: directory
        owner: bot
        group: bot
        mode: "0700"

    - name: Deploy S/MIME private key
      copy:
        content: "{{ smime_private_key }}"
        dest: /var/www/e-ticket/config/cert/private-key.pem
        owner: bot
        group: bot
        mode: "0600"

    - name: Pull latest code
      command: git pull origin master
      args:
        chdir: /var/www/e-ticket
      become_user: bot

    - name: Deploy PgBouncer config
      template:
        src: pgbouncer.ini.j2
        dest: /var/www/e-ticket/docker/pgsql/pgbouncer.ini
        owner: bot
        group: bot
        mode: "0644"

    - name: Deploy PgBouncer userlist
      template:
        src: userlist.txt.j2
        dest: /var/www/e-ticket/docker/pgsql/userlist.txt
        owner: bot
        group: bot
        mode: "0644"

    - name: Deploy docker-compose-prod.yml
      template:
        src: docker-compose-prod.yml.j2
        dest: /var/www/e-ticket/docker-compose-prod.yml
        owner: bot
        group: bot
        mode: "0600"

    - name: Build Docker images
      command: make build_prod
      args:
        chdir: /var/www/e-ticket

    - name: Pull Docker images
      command: make pull_prod
      args:
        chdir: /var/www/e-ticket

    - name: Stop production containers
      command: make stop_prod
      args:
        chdir: /var/www/e-ticket

    - name: Start production containers
      command: make start_prod
      args:
        chdir: /var/www/e-ticket

    - name: Install PHP dependencies
      command: composer install --no-dev --optimize-autoloader
      args:
        chdir: /var/www/e-ticket
      become_user: bot

    - name: Install JS dependencies
      command: bun install
      args:
        chdir: /var/www/e-ticket
      become_user: bot

    - name: Build assets
      command: bun run build
      args:
        chdir: /var/www/e-ticket
      become_user: bot

    - name: Wait for database to be ready
      shell: |
        for i in $(seq 1 30); do
          docker compose -f docker-compose-prod.yml exec -T php php -r "new PDO('pgsql:host=pgbouncer;port=6432;dbname=e-ticket','e-ticket','{{ db_password }}');" 2>/dev/null && exit 0
          sleep 1
        done
        exit 1
      args:
        chdir: /var/www/e-ticket

    - name: Clear Symfony cache before migration
      command: docker compose -f docker-compose-prod.yml exec -T php php bin/console cache:clear --env=prod
      args:
        chdir: /var/www/e-ticket

    - name: Clear Redis cache pool (Doctrine L2 + app cache)
      command: docker compose -f docker-compose-prod.yml exec -T php php bin/console cache:pool:clear cache.app --env=prod
      args:
        chdir: /var/www/e-ticket

    - name: Run migrations
      command: make migrate_prod
      args:
        chdir: /var/www/e-ticket

    - name: Clear cache after migration
      command: make clear_prod
      args:
        chdir: /var/www/e-ticket

    - name: Compile PWA assets
      command: make pwa_prod
      args:
        chdir: /var/www/e-ticket

    - name: Ensure uploads directories exist with correct permissions
      file:
        path: "/var/www/e-ticket/public/uploads/{{ item }}"
        state: directory
        owner: "1000"
        group: "1000"
        mode: "0755"
        recurse: true
      loop:
        - logos

    - name: Ensure var/payouts directory exists
      file:
        path: /var/www/e-ticket/var/payouts
        state: directory
        owner: "1000"
        group: "1000"
        mode: "0755"

    - name: Ensure Caddy sites directory exists
      file:
        path: /etc/caddy/sites
        state: directory
        owner: root
        group: root
        mode: "0755"

    - name: Deploy Caddy config
      template:
        src: caddy.j2
        dest: /etc/caddy/sites/e-ticket.conf
        owner: root
        group: root
        mode: "0644"
      notify: Reload Caddy

    - name: Create backup directory
      file:
        path: /var/backups/e-ticket
        state: directory
        owner: bot
        group: bot
        mode: "0750"

    - name: Deploy backup script
      template:
        src: backup.sh.j2
        dest: /var/backups/e-ticket/backup.sh
        owner: bot
        group: bot
        mode: "0750"

    - name: Configure backup cron (every 30 minutes)
      cron:
        name: "e-ticket database backup"
        minute: "*/30"
        job: "/var/backups/e-ticket/backup.sh >> /var/log/e-ticket-backup.log 2>&1"
        user: bot

    - name: Configure expire pending orders cron (every 5 minutes)
      cron:
        name: "e-ticket expire pending orders"
        minute: "*/5"
        job: "docker compose -f /var/www/e-ticket/docker-compose-prod.yml exec -T php php bin/console app:orders:expire-pending --env=prod >> /var/log/e-ticket-expire-orders.log 2>&1"
        user: bot

    - name: Configure messenger monitor cron (every hour)
      cron:
        name: "e-ticket messenger monitor"
        minute: "0"
        job: "docker compose -f /var/www/e-ticket/docker-compose-prod.yml exec -T php php bin/console app:monitor:messenger --env=prod >> /var/log/e-ticket-messenger.log 2>&1"
        user: bot

    - name: Configure Meilisearch consistency check cron (daily at 3am)
      cron:
        name: "e-ticket meilisearch consistency"
        minute: "0"
        hour: "3"
        job: "docker compose -f /var/www/e-ticket/docker-compose-prod.yml exec -T php php bin/console app:meilisearch:check-consistency --fix --env=prod >> /var/log/e-ticket-meilisearch.log 2>&1"
        user: bot

    - name: Configure Stripe sync cron (every 6 hours)
      cron:
        name: "e-ticket stripe sync"
        minute: "0"
        hour: "*/6"
        job: "docker compose -f /var/www/e-ticket/docker-compose-prod.yml exec -T php php bin/console app:stripe:sync --env=prod >> /var/log/e-ticket-stripe-sync.log 2>&1"
        user: bot

    - name: Configure infra snapshot cron (every 5 minutes)
      cron:
        name: "e-ticket infra snapshot"
        minute: "*/5"
        job: "docker compose -f /var/www/e-ticket/docker-compose-prod.yml exec -T php php bin/console app:infra:snapshot --env=prod >> /var/log/e-ticket-infra.log 2>&1"
        user: bot

  post_tasks:
    - name: Disable maintenance mode
      command: make maintenance_off
      args:
        chdir: /var/www/e-ticket

  handlers:
    - name: Reload Caddy
      systemd:
        name: caddy
        state: reloaded

