- name: Deploy Learning Platform with Ansible
  hosts: all
  become: yes
  gather_facts: yes
  vars:
    ansible_ssh_common_args: '-o StrictHostKeyChecking=no'

  tasks:
    - name: Set destination directory
      ansible.builtin.set_fact:
        dest_dir: "/opt/learning-platform"

    - name: Ensure dependencies are installed
      ansible.builtin.package:
        name:
          - docker-ce
        state: present
      ignore_errors: yes
      register: docker_valid

    - name: Include geerlingguy.docker role conditionally
      include_role:
        name: geerlingguy.docker
      when: docker_valid is failed

    - name: Ensure target directory exists
      ansible.builtin.file:
        path: "{{ dest_dir }}"
        state: directory
        owner: root
        group: root
        mode: "0755"

    - name: Copy compose.yml to destination
      ansible.builtin.copy:
        src: compose.yml
        dest: "{{ dest_dir }}/compose.yml"

    - name: Pull latest image
      community.docker.docker_compose_v2:
        project_src: "{{ dest_dir }}"
        state: present
        files: compose.yml
        pull: always

    - name: Start services with Docker Compose
      community.docker.docker_compose_v2:
        project_src: "{{ dest_dir }}"
        state: present
        files: compose.yml
        recreate: always
