name: Internal Links Check

on:
  pull_request:
    paths:
      - 'docs/**'
      - '**/*.md'
      - '.github/workflows/links-check.yml'

permissions:
  contents: read

jobs:
  linkChecker:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Check out repo
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
        with:
          persist-credentials: false
          fetch-depth: 0

      # It will be possible to check only for the links in the changed files
      # See: https://github.com/lycheeverse/lychee-action/issues/17
      - name: Link Checker
        id: lychee
        uses: lycheeverse/lychee-action@8646ba30535128ac92d33dfc9133794bfdd9b411 # 2.8.0
        with:
          fail: true
          # As external links behavior is not predictable, we check only internal links
          # to ensure consistency.
          # See: https://github.com/lycheeverse/lychee-action/issues/17#issuecomment-1162586751
          args: --offline --verbose --no-progress --root-dir "$(pwd)" './**/*.md'
        env:
          GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}

      - name: Collect changed markdown files
        id: changed-md
        run: |
          # docs/Guides/Ecosystem.md is checked by scripts/validate-ecosystem-links.js
          changed_files=$(git diff --name-only --diff-filter=ACMRT "${{ github.event.pull_request.base.sha }}" "${{ github.event.pull_request.head.sha }}" | grep -E '\.md$' | grep -v '^docs/Guides/Ecosystem\.md$' || true)

          if [ -z "$changed_files" ]; then
            echo "files=" >> "$GITHUB_OUTPUT"
            echo "No markdown files to check with linkinator."
            exit 0
          fi

          files_as_space_list=$(echo "$changed_files" | tr '\n' ' ' | xargs)
          echo "files=$files_as_space_list" >> "$GITHUB_OUTPUT"
          echo "Checking markdown files: $files_as_space_list"

      - name: External Link Checker
        if: steps.changed-md.outputs.files != ''
        uses: JustinBeckwith/linkinator-action@7b6b0bc671f6264e1a8daa4488a5bd91ce61dcd4 # 2.4.2
        with:
          paths: ${{ steps.changed-md.outputs.files }}
          serverRoot: ${{ github.workspace }}
          retry: true
          redirects: error
          verbosity: error
          linksToSkip: "https://github.com/orgs/fastify/.*,https://github.com/fastify/fastify/security/advisories/new"
          statusCodes: '{"403":"warn"}'