- name: Gather OS facts
  ansible.builtin.setup:
    filter: ansible_distribution
  register: os_facts

- name: Import Microsoft GPG key (Fedora)
  ansible.builtin.rpm_key:
    key: https://packages.microsoft.com/keys/microsoft.asc
  when: os_facts.ansible_facts.ansible_distribution == 'Fedora'

- name: Add VSCode repository (Fedora)
  ansible.builtin.copy:
    content: |
      [code]
      name=Visual Studio Code
      baseurl=https://packages.microsoft.com/yumrepos/vscode
      enabled=1
      gpgcheck=1
      gpgkey=https://packages.microsoft.com/keys/microsoft.asc
    dest: /etc/yum.repos.d/vscode.repo
    mode: '0644'
  when: os_facts.ansible_facts.ansible_distribution == 'Fedora'

- name: Add VSCode repository (Ubuntu/Debian)
  ansible.builtin.apt_repository:
    repo: 'deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main'
    state: present
  when: os_facts.ansible_facts.ansible_distribution in ['Ubuntu', 'Debian']

- name: Import Microsoft GPG key (Ubuntu/Debian)
  ansible.builtin.apt_key:
    url: https://packages.microsoft.com/keys/microsoft.asc
    state: present
  when: os_facts.ansible_facts.ansible_distribution in ['Ubuntu', 'Debian']

- name: Check if VSCode is installed
  ansible.builtin.command: code --version
  register: vscode_check
  changed_when: false
  failed_when: false

- name: Install VSCode (Fedora)
  ansible.builtin.package:
    name: code
    state: present
  when: vscode_check.rc != 0 and os_facts.ansible_facts.ansible_distribution == 'Fedora'

- name: Install VSCode (Ubuntu/Debian)
  ansible.builtin.apt:
    name: code
    state: present
  when: vscode_check.rc != 0 and os_facts.ansible_facts.ansible_distribution in ['Ubuntu', 'Debian']
