name: Get Changed Files

on:
  workflow_call:
    inputs:
      all_files:
        description: "Whether to return all files instead of just changed files"
        required: false
        type: boolean
        default: false
    outputs:
      changed-files:
        description: "List of changed files (space-separated) or '*' if not in a PR"
        value: ${{ jobs.get-changed-files.outputs.changed-files }}

jobs:
  get-changed-files:
    runs-on: ubuntu-latest
    outputs:
      changed-files: ${{ steps.get-files.outputs.changed-files }}

    steps:
      - name: Get changed files
        id: get-files
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          # Check if we're in a pull request context
          if [ "${{ github.event_name }}" = "pull_request" ] || [ "${{ github.event_name }}" = "pull_request_target" ]; then
            echo "Running in PR context"

            # Get the PR number from the github context
            PR_NUMBER="${{ github.event.number }}"

            # Check if all_files is requested
            if [ "${{ inputs.all_files }}" = "true" ]; then
              echo "all_files input is true, returning all files"
              echo "changed-files=*" >> "$GITHUB_OUTPUT"
            else
              # Use gh CLI to get changed files in the PR with explicit repo
              CHANGED_FILES=$(gh api repos/${{ github.repository }}/pulls/$PR_NUMBER/files --paginate --jq '.[] | select(.status != "removed") | .filename' | tr '\n' ' ' | sed 's/ $//')

              if [ -z "$CHANGED_FILES" ]; then
                echo "No changed files found, setting to '*'"
                CHANGED_FILES="*"
              fi

              echo "Changed files: $CHANGED_FILES"
              echo "changed-files=$CHANGED_FILES" >> "$GITHUB_OUTPUT"
            fi

          else
            echo "Not in PR context, setting changed files to '*'"
            echo "changed-files=*" >> "$GITHUB_OUTPUT"
          fi
