---
# Rolling upgrade of Changemaker Lite instances
# Usage: ansible-playbook playbooks/upgrade.yml [--limit hostname]
# Pulls latest code, rebuilds images, runs migrations, restarts

- name: Upgrade Changemaker Lite
  hosts: changemaker_instances
  serial: "25%"  # Rolling upgrade in batches
  become: true

  tasks:
    - name: Pull latest code
      ansible.builtin.git:
        repo: "{{ cml_repo_url }}"
        dest: "{{ cml_deploy_path }}"
        version: "{{ cml_repo_branch }}"
        force: false
        update: true
      register: git_result

    - name: Regenerate .env (pick up new vars)
      ansible.builtin.template:
        src: "{{ playbook_dir }}/../roles/changemaker/templates/env.j2"
        dest: "{{ cml_deploy_path }}/.env"
        mode: "0600"
        backup: true

    - name: Pull updated Docker images
      ansible.builtin.command:
        cmd: docker compose pull
        chdir: "{{ cml_deploy_path }}"
      changed_when: true

    - name: Rebuild custom images
      ansible.builtin.command:
        cmd: docker compose build --no-cache
        chdir: "{{ cml_deploy_path }}"
      changed_when: true
      when: git_result.changed

    - name: Apply database migrations
      ansible.builtin.command:
        cmd: docker compose exec -T api npx prisma migrate deploy
        chdir: "{{ cml_deploy_path }}"
      register: migrate_result
      changed_when: "'applied' in migrate_result.stdout"

    - name: Restart stack with new images
      ansible.builtin.command:
        cmd: docker compose up -d --remove-orphans
        chdir: "{{ cml_deploy_path }}"
      changed_when: true

    - name: Restart monitoring (if enabled)
      ansible.builtin.command:
        cmd: docker compose --profile monitoring up -d
        chdir: "{{ cml_deploy_path }}"
      when: cml_monitoring_enabled | bool
      changed_when: true

    - name: Wait for API health
      ansible.builtin.uri:
        url: "http://localhost:{{ cml_api_port }}/api/health"
        method: GET
        status_code: 200
        timeout: 5
      register: health
      retries: 15
      delay: 3
      until: health.status == 200

    - name: Upgrade summary
      ansible.builtin.debug:
        msg: |
          Upgraded {{ cml_domain }}
          Git: {{ git_result.before[:8] | default('?') }} → {{ git_result.after[:8] | default('?') }}
          Migrations: {{ migrate_result.stdout_lines | default([]) | length }} applied
          API health: OK
