name: Markdown Link Check

on:
  workflow_call:
    inputs:
      soft-fail:
        description: 'Whether to continue on broken links'
        required: false
        type: boolean
        default: false

permissions:
  contents: read

jobs:
  markdown-link-check:
    name: Check Markdown Links
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - name: Checkout code
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4.2.2
        with:
          persist-credentials: false

      - name: Setup Node.js
        uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v4.1.0
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Create logs directory
        shell: pwsh
        run: |
          New-Item -ItemType Directory -Force -Path logs | Out-Null

      - name: Run markdown link check
        id: link-check
        shell: pwsh
        run: |
          & scripts/linting/Markdown-Link-Check.ps1
        continue-on-error: ${{ inputs.soft-fail }}

      - name: Upload markdown link check results
        if: always()
        uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v4.4.3
        with:
          name: markdown-link-check-results
          path: logs/markdown-link-check-results.json
          retention-days: 30

      - name: Check results and fail if needed
        if: ${{ !inputs.soft-fail && steps.link-check.outcome == 'failure' }}
        shell: pwsh
        run: |
          Write-Host "Markdown link check failed and soft-fail is false. Failing the job."
          exit 1
