name: UI Deployment
on:
  push:
    branches:
      - master
  pull_request:
    paths:
      - 'packages/explorer-ui/**'
      - 'docs/bridge/**'
      - 'packages/synapse-interface/**'
      - 'packages/synapse-constants/**'
jobs:
  changes:
    runs-on: ubuntu-latest
    outputs:
      # Expose matched filters as job 'packages' output variable
      packages: ${{ steps.filter_ui.outputs.changes }}
      package_count: ${{ steps.length.outputs.FILTER_LENGTH }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          # if any of these packages use submodules in the future, please uncomment this line
          # submodules: 'recursive'
      - uses: dorny/paths-filter@v3
        id: filter_ui
        with:
          #  make sure to update run-goreleaser when adding a new package here
          # also add to the get-project-id step
          filters: |
            explorer-ui: 'packages/explorer-ui/**'
            docs: 'docs/bridge/**'
            synapse-interface: 'packages/synapse-interface/**'
      - id: length
        run: |
          export FILTER_LENGTH=$(echo $FILTERED_PATHS | jq '. | length')
          echo "FILTER_LENGTH=$FILTER_LENGTH" >> "$GITHUB_OUTPUT"
        env:
          FILTERED_PATHS: ${{ steps.filter_ui.outputs.changes }}
  # for details on how to use, please see ui-preview.md
  deploy:
    name: Deploy to Vercel
    runs-on: ubuntu-latest
    needs: changes
    if: ${{ needs.changes.outputs.package_count > 0 }}
    strategy:
      fail-fast: false
      matrix:
        package: ${{ fromJson(needs.changes.outputs.packages) }}
    env:
      # TODO: this appears to work even if package is not in packages/[package]
      # (see the addition of docs for details). It's possible workign directory can be removd.
      WORKING_DIRECTORY: 'packages/${{matrix.package}}'
      GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}'
      VERCEL_TOKEN: '${{ secrets.VERCEL_TOKEN }}'
      VERCEL_ORG_ID: '${{ secrets.VERCEL_ORG_ID }}'
      NODE_ENV: 'production'
    steps:
      - uses: actions/checkout@v4
      - name: Setup NodeJS
        uses: ./.github/actions/setup-nodejs
        with:
          cache: 'npm'
          install_dependencies: 'false'
          cache-path: ''
      - name: Build synapse-constants
        run: |
          cd packages/synapse-constants
          yarn install
          yarn build
        working-directory: ${{ github.workspace }}
      - name: Get Project ID
        id: project_id
        # see: https://stackoverflow.com/a/75231888 for details
        run: |
          PROJECT_IDS=$(cat <<END
          {
            "explorer-ui": "${{ secrets.VERCEL_PROJECT_ID}}",
            "docs": "${{ secrets.DOCS_VERCEL_PROJECT_ID }}",
            "synapse-interface": "${{ secrets.SYNAPSE_INTERFACE_PROJECT_ID }}"
          }
          END
          )
          TARGET_ID=$(echo $PROJECT_IDS | jq -r 'to_entries[] | select(.key=="${{ matrix.package }}") | .value')
          # set the vercel project id`
          echo "VERCEL_PROJECT_ID=$TARGET_ID" >> $GITHUB_ENV
      - name: Install Vercel CLI
        run: npm install --global vercel@32.5.3
      - name: Deploy to Vercel (Output Preview/Inspect Links)
        if: ${{ format('refs/heads/{0}', github.event.repository.default_branch) != github.ref }}
        id: deploy
        run: |
          vercel pull --yes --environment=preview --token=${{ secrets.VERCEL_TOKEN }}
          vercel build --token=${{ secrets.VERCEL_TOKEN }}
          export DEPLOY_URL=$(vercel deploy --prebuilt --token=${{ secrets.VERCEL_TOKEN }})
          echo "DEPLOY_URL=$DEPLOY_URL" >> $GITHUB_ENV
          echo "::set-output name=url::$DEPLOY_URL"
        env:
          CODECOV_TOKEN: ${{ secrets.CODECOV }}
          GH_COMMIT_SHA: ${{ github.event.pull_request.head.sha }}
      - name: Deploy to Vercel (Output Prod)
        if: ${{ format('refs/heads/{0}', github.event.repository.default_branch) == github.ref }}
        run: |
          vercel pull --yes --environment=preview --token=${{ secrets.VERCEL_TOKEN }}
          vercel build --token=${{ secrets.VERCEL_TOKEN }} --prod
          vercel deploy --prebuilt --token=${{ secrets.VERCEL_TOKEN }} --prod
        env:
          CODECOV_TOKEN: ${{ secrets.CODECOV }}
          GH_COMMIT_SHA: ${{ github.event.pull_request.head.sha }}

      - name: Update PR Description
        if: ${{ github.event_name == 'pull_request' && format('refs/heads/{0}', github.event.repository.default_branch) != github.ref }}
        uses: actions/github-script@v3
        with:
          script: |
            const {data: pullRequest} = await github.pulls.get({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: context.issue.number
            });
            const newBody = `${pullRequest.body}\n${{github.sha}}: [${{matrix.package}} preview link ](${{ steps.deploy.outputs.url }})`;
            await github.pulls.update({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: context.issue.number,
              body: newBody
            });