---
- name: GlitchTip Fetch Last Errors
  hosts: optovia_servers
  gather_facts: no

  # Usage:
  # ansible-playbook -i ansible/inventory/production/hosts.yml ansible/playbooks/glitchtip_check_errors.yml \
  #   -e "glitchtip_org=org-slug glitchtip_project=project-slug glitchtip_token=XXX [glitchtip_host=https://bugs.dsrptlab.com] [limit=10]"

  vars:
    glitchtip_default_host: "https://bugs.dsrptlab.com"
    glitchtip_limit: "{{ limit | default(10) }}"
    glitchtip_inventory_host: "{{ groups['optovia_servers'][0] | default(None) }}"
    repo_root: "{{ playbook_dir | dirname | dirname }}"

  pre_tasks:
    - name: Collect GlitchTip parameters
      run_once: true
      delegate_to: localhost
      set_fact:
        glitchtip_org_value: >-
          {{ glitchtip_org
             | default(lookup('env', 'GLITCHTIP_ORG'))
             | default(hostvars.get(glitchtip_inventory_host, {}).get('glitchtip_org'))
          }}
        glitchtip_project_value: >-
          {{ glitchtip_project
             | default(lookup('env', 'GLITCHTIP_PROJECT'))
             | default(hostvars.get(glitchtip_inventory_host, {}).get('glitchtip_project'))
          }}
        glitchtip_token_value: >-
          {{ glitchtip_token
             | default(lookup('env', 'GLITCHTIP_TOKEN'))
             | default(hostvars.get(glitchtip_inventory_host, {}).get('glitchtip_token'))
          }}
        glitchtip_host_value: "{{ (glitchtip_host | default(glitchtip_default_host)) | regex_replace('/+$', '') }}"

    - name: Validate required parameters
      run_once: true
      delegate_to: localhost
      assert:
        that:
          - glitchtip_org_value is defined
          - glitchtip_org_value | length > 0
          - glitchtip_project_value is defined
          - glitchtip_project_value | length > 0
          - glitchtip_token_value is defined
          - glitchtip_token_value | length > 0
        fail_msg: "Required vars: glitchtip_org, glitchtip_project, glitchtip_token (or env GLITCHTIP_ORG/PROJECT/TOKEN)."

    - name: Set generated timestamp
      run_once: true
      delegate_to: localhost
      set_fact:
        glitchtip_generated_at: "{{ lookup('pipe', 'date -u +%Y-%m-%dT%H:%M:%SZ') }}"

  tasks:
    - name: Fetch last GlitchTip errors
      run_once: true
      delegate_to: localhost
      uri:
        url: "{{ glitchtip_host_value }}/api/0/projects/{{ glitchtip_org_value }}/{{ glitchtip_project_value }}/issues/?limit={{ glitchtip_limit }}"
        method: GET
        headers:
          Authorization: "Bearer {{ glitchtip_token_value }}"
          Accept: "application/json"
        return_content: yes
        status_code: 200
        validate_certs: yes
      register: glitchtip_response

    - name: Show last errors
      run_once: true
      delegate_to: localhost
      debug:
        msg: "{{ item.id }} | {{ item.title }} | culprit={{ item.culprit }} | lastSeen={{ item.lastSeen }} | permalink={{ item.permalink }}"
      loop: "{{ glitchtip_response.json | default([]) }}"
      loop_control:
        label: "{{ item.id | default('issue') }}"

    - name: Fetch latest event per issue
      run_once: true
      delegate_to: localhost
      uri:
        url: "{{ glitchtip_host_value }}/api/0/issues/{{ item.id }}/events/latest/"
        method: GET
        headers:
          Authorization: "Bearer {{ glitchtip_token_value }}"
          Accept: "application/json"
        return_content: yes
        status_code: 200
        validate_certs: yes
      loop: "{{ glitchtip_response.json | default([]) }}"
      loop_control:
        label: "{{ item.id | default('issue') }}"
      register: issue_events

    - name: Accumulate events payload
      run_once: true
      delegate_to: localhost
      set_fact:
        glitchtip_events_payload: "{{ glitchtip_events_payload | default([]) + [ {'issue': item.item, 'event': item.json} ] }}"
      loop: "{{ issue_events.results | default([]) }}"
      loop_control:
        label: "{{ item.item.id | default('issue') }}"

    - name: Save combined issues/events JSON to repo root
      run_once: true
      delegate_to: localhost
      copy:
        dest: "{{ repo_root }}/glitchtip_last_errors.json"
        content: >-
          {{ {
              'generated_at': glitchtip_generated_at,
              'host': glitchtip_host_value,
              'org': glitchtip_org_value,
              'project': glitchtip_project_value,
              'issues': glitchtip_response.json | default([]),
              'latest_events': glitchtip_events_payload | default([])
            } | to_nice_json }}
        mode: '0644'
