name: Netlify deploy

on:
  push:
    branches:
      - main
      - staging
      - "staging/**"
      - "web-requests/**"
  pull_request:
    branches:
      - main
      - staging
  workflow_dispatch:

permissions:
  contents: read
  pull-requests: write

env:
  NETLIFY_SITE_ID: e20cb60a-0bfa-48dc-9e8e-5925b0c86ccd

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Check out repository
        uses: actions/checkout@v4

      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Build site
        run: npm run build

      - name: Deploy to Netlify
        id: deploy
        env:
          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
        run: |
          set -euo pipefail

          if [ -z "${NETLIFY_AUTH_TOKEN:-}" ]; then
            echo "NETLIFY_AUTH_TOKEN is not configured as a repository secret." >&2
            exit 1
          fi

          branch="${GITHUB_HEAD_REF:-${GITHUB_REF_NAME}}"
          alias="$(printf '%s' "$branch" \
            | tr '[:upper:]' '[:lower:]' \
            | sed -E 's/[^a-z0-9-]+/-/g; s/^-+//; s/-+$//' \
            | cut -c 1-37)"

          if [ -z "$alias" ]; then
            alias="preview"
          fi

          if [ "${GITHUB_EVENT_NAME}" = "push" ] && [ "${GITHUB_REF_NAME}" = "main" ]; then
            deploy_json="$(npx netlify-cli@latest deploy --site "$NETLIFY_SITE_ID" --prod --dir=dist --json --message "Production deploy from ${GITHUB_SHA}")"
          else
            deploy_json="$(npx netlify-cli@latest deploy --site "$NETLIFY_SITE_ID" --dir=dist --alias "$alias" --json --message "Preview deploy for ${branch} at ${GITHUB_SHA}")"
          fi

          printf '%s\n' "$deploy_json"
          deploy_url="$(node -e 'const data = JSON.parse(process.argv[1]); console.log(data.deploy_url || data.deployUrl || data.deploy_ssl_url || data.ssl_url || data.url || "")' "$deploy_json")"

          if [ -n "$deploy_url" ]; then
            echo "deploy_url=$deploy_url" >> "$GITHUB_OUTPUT"
            echo "### Netlify deploy" >> "$GITHUB_STEP_SUMMARY"
            echo "" >> "$GITHUB_STEP_SUMMARY"
            echo "$deploy_url" >> "$GITHUB_STEP_SUMMARY"
          fi

      - name: Comment preview URL on pull request
        if: github.event_name == 'pull_request' && steps.deploy.outputs.deploy_url != ''
        uses: actions/github-script@v7
        with:
          script: |
            const body = `Netlify preview deploy is ready:\n\n${{ steps.deploy.outputs.deploy_url }}`;
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body,
            });
