name: Next.js Build Check

on:
  pull_request:
    paths:
      - 'js/cf-webapp/**'

permissions:
  contents: read
  pull-requests: read

jobs:
  # This job checks if the workflow should run based on file changes
  check-changes:
    runs-on: ubuntu-latest
    outputs:
      should-run: ${{ steps.filter.outputs.webapp }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: dorny/paths-filter@v3
        id: filter
        with:
          filters: |
            webapp:
              - 'js/cf-webapp/**'

  # This job always runs and succeeds, allowing PRs to be merged when paths don't match
  skip-build:
    needs: check-changes
    if: needs.check-changes.outputs.should-run != 'true'
    runs-on: ubuntu-latest
    steps:
      - name: Skip build
        run: echo "Skipping Next.js build - no changes in js/cf-webapp/"

  build:
    needs: check-changes
    if: needs.check-changes.outputs.should-run == 'true'
    env:
      NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: read

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          registry-url: https://npm.pkg.github.com
          scope: '@codeflash-ai'

      - name: Install dependencies
        run: |
          cd js/cf-webapp
          # Install dependencies but skip prepare scripts
          npm ci --ignore-scripts

      - name: Build Next.js app
        run: |
          cd js/cf-webapp
          # First generate Prisma client
          npx prisma generate
          # Then build the Next.js app
          npx next build
