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

  pre_tasks:
    - name: Enable maintenance mode
      command: make maintenance_on
      args:
        chdir: /var/www/crm-siteconseil

    - 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/crm-siteconseil/.env.local
        owner: bot
        group: bot
        mode: "0600"

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

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

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

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

    - name: Deploy PgBouncer userlist
      template:
        src: userlist.txt.j2
        dest: /var/www/crm-siteconseil/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/crm-siteconseil/docker-compose-prod.yml
        owner: bot
        group: bot
        mode: "0600"

    - name: Build Docker images
      command: make build_prod
      args:
        chdir: /var/www/crm-siteconseil

    - name: Pull Docker images
      command: make pull_prod
      args:
        chdir: /var/www/crm-siteconseil

    - name: Stop production containers
      command: make stop_prod
      args:
        chdir: /var/www/crm-siteconseil

    - name: Start production containers
      command: make start_prod
      args:
        chdir: /var/www/crm-siteconseil

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

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

    - name: Build assets
      command: bun run build
      args:
        chdir: /var/www/crm-siteconseil
      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=crm-siteconseil','crm-siteconseil','{{ db_password }}');" 2>/dev/null && exit 0
          sleep 1
        done
        exit 1
      args:
        chdir: /var/www/crm-siteconseil

    - 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/crm-siteconseil

    - 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/crm-siteconseil

    - name: Run migrations
      command: make migrate_prod
      args:
        chdir: /var/www/crm-siteconseil

    - name: Clear cache after migration
      command: make clear_prod
      args:
        chdir: /var/www/crm-siteconseil

    - name: Compile PWA assets
      command: make pwa_prod
      args:
        chdir: /var/www/crm-siteconseil

    - name: Ensure uploads directories exist with correct permissions
      file:
        path: "/var/www/crm-siteconseil/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/crm-siteconseil/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/crm-siteconseil.conf
        owner: root
        group: root
        mode: "0644"
      notify: Reload Caddy

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

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

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

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

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

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

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

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

    - name: Configure attestations cleanup cron (daily at 4am)
      cron:
        name: "crm-siteconseil attestations clean"
        minute: "0"
        hour: "4"
        job: "docker compose -f /var/www/crm-siteconseil/docker-compose-prod.yml exec -T php php bin/console app:attestations:clean --env=prod >> /var/log/crm-siteconseil-attestations.log 2>&1"
        user: bot

    - name: Configure services health check cron (every 15 minutes)
      cron:
        name: "crm-siteconseil services check"
        minute: "*/15"
        job: "docker compose -f /var/www/crm-siteconseil/docker-compose-prod.yml exec -T php php bin/console app:services:check --env=prod >> /var/log/crm-siteconseil-services.log 2>&1"
        user: bot

    - name: Configure DNS check cron (every 2 hours)
      cron:
        name: "crm-siteconseil dns check"
        minute: "0"
        hour: "*/2"
        job: "docker compose -f /var/www/crm-siteconseil/docker-compose-prod.yml exec -T php php bin/console app:dns:check --env=prod >> /var/log/crm-siteconseil-dns-check.log 2>&1"
        user: bot

    - name: Configure email tracking purge cron (daily at 5am)
      cron:
        name: "crm-siteconseil email-tracking purge"
        minute: "0"
        hour: "5"
        job: "docker compose -f /var/www/crm-siteconseil/docker-compose-prod.yml exec -T php php bin/console app:email-tracking:purge --env=prod >> /var/log/crm-siteconseil-email-purge.log 2>&1"
        user: bot

    - name: Configure Cloudflare acme-challenge cleanup cron (daily at 6am)
      cron:
        name: "crm-siteconseil cloudflare clean"
        minute: "0"
        hour: "6"
        job: "docker compose -f /var/www/crm-siteconseil/docker-compose-prod.yml exec -T php php bin/console app:cloudflare:clean --env=prod >> /var/log/crm-siteconseil-cloudflare-clean.log 2>&1"
        user: bot

    - name: Configure pending delete cleanup cron (daily at 2am)
      cron:
        name: "crm-siteconseil clean pending delete"
        minute: "0"
        hour: "2"
        job: "docker compose -f /var/www/crm-siteconseil/docker-compose-prod.yml exec -T php php bin/console app:clean:pending-delete --env=prod >> /var/log/crm-siteconseil-clean-pending.log 2>&1"
        user: bot

    - name: Configure NDD expiration check cron (daily at 8am)
      cron:
        name: "crm-siteconseil ndd check"
        minute: "0"
        hour: "8"
        job: "docker compose -f /var/www/crm-siteconseil/docker-compose-prod.yml exec -T php php bin/console app:ndd:check --env=prod >> /var/log/crm-siteconseil-ndd-check.log 2>&1"
        user: bot

    - name: Configure payment reminder cron (daily at 9am)
      cron:
        name: "crm-siteconseil payment reminder"
        minute: "0"
        hour: "9"
        job: "docker compose -f /var/www/crm-siteconseil/docker-compose-prod.yml exec -T php php bin/console app:payment:reminder --env=prod >> /var/log/crm-siteconseil-payment-reminder.log 2>&1"
        user: bot

    - name: Configure Meilisearch full reindex cron (weekly Sunday at 4am)
      cron:
        name: "crm-siteconseil meilisearch reindex"
        minute: "0"
        hour: "4"
        weekday: "0"
        job: "docker compose -f /var/www/crm-siteconseil/docker-compose-prod.yml exec -T php php bin/console app:meilisearch:setup --env=prod >> /var/log/crm-siteconseil-meilisearch-reindex.log 2>&1"
        user: bot

  post_tasks:
    - name: Disable maintenance mode
      command: make maintenance_off
      args:
        chdir: /var/www/crm-siteconseil

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

