name: Log GitHub Issue Events

on:
  issues:
    types: [opened]

jobs:
  log-issue-created:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      contents: read
      issues: read

    steps:
      - name: Log issue creation to Statsig
        env:
          STATSIG_API_KEY: ${{ secrets.STATSIG_API_KEY }}
        run: |
          ISSUE_NUMBER=${{ github.event.issue.number }}
          REPO=${{ github.repository }}
          ISSUE_TITLE="${{ github.event.issue.title }}"
          AUTHOR="${{ github.event.issue.user.login }}"
          CREATED_AT="${{ github.event.issue.created_at }}"
          
          if [ -z "$STATSIG_API_KEY" ]; then
            echo "STATSIG_API_KEY not found, skipping Statsig logging"
            exit 0
          fi
          
          # Prepare the event payload
          EVENT_PAYLOAD=$(jq -n \
            --arg issue_number "$ISSUE_NUMBER" \
            --arg repo "$REPO" \
            --arg title "$ISSUE_TITLE" \
            --arg author "$AUTHOR" \
            --arg created_at "$CREATED_AT" \
            '{
              events: [{
                eventName: "github_issue_created",
                value: 1,
                metadata: {
                  repository: $repo,
                  issue_number: ($issue_number | tonumber),
                  issue_title: $title,
                  issue_author: $author,
                  created_at: $created_at
                },
                time: (now | floor | tostring)
              }]
            }')
          
          # Send to Statsig API
          echo "Logging issue creation to Statsig for issue #${ISSUE_NUMBER}"
          
          RESPONSE=$(curl -s -w "\n%{http_code}" -X POST https://events.statsigapi.net/v1/log_event \
            -H "Content-Type: application/json" \
            -H "STATSIG-API-KEY: ${STATSIG_API_KEY}" \
            -d "$EVENT_PAYLOAD")
          
          HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
          BODY=$(echo "$RESPONSE" | head -n-1)
          
          if [ "$HTTP_CODE" -eq 200 ] || [ "$HTTP_CODE" -eq 202 ]; then
            echo "Successfully logged issue creation for issue #${ISSUE_NUMBER}"
          else
            echo "Failed to log issue creation for issue #${ISSUE_NUMBER}. HTTP ${HTTP_CODE}: ${BODY}"
          fi