---
# Deploy Docker Compose stack

- name: Pull latest images
  ansible.builtin.command:
    cmd: docker compose pull
    chdir: "{{ cml_deploy_path }}"
  changed_when: true
  tags: [pull]

- name: Build custom images
  ansible.builtin.command:
    cmd: docker compose build --no-cache
    chdir: "{{ cml_deploy_path }}"
  changed_when: true
  tags: [build]

- name: Start core services
  ansible.builtin.command:
    cmd: docker compose up -d --remove-orphans
    chdir: "{{ cml_deploy_path }}"
  changed_when: true

- name: Wait for PostgreSQL to be ready
  ansible.builtin.command:
    cmd: docker compose exec -T v2-postgres pg_isready -U {{ cml_v2_postgres_user }}
    chdir: "{{ cml_deploy_path }}"
  register: pg_ready
  retries: 15
  delay: 2
  until: pg_ready.rc == 0
  changed_when: false

- name: Run Prisma 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: Run database seed (first deploy only)
  ansible.builtin.command:
    cmd: docker compose exec -T api npx prisma db seed
    chdir: "{{ cml_deploy_path }}"
  register: seed_result
  changed_when: "'created' in seed_result.stdout"
  failed_when: false

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