name: Build

on:
  workflow_dispatch:
    inputs:
      branch:
        description: 'Branch to build'
        required: true
        default: 'main'

permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 10

    steps:
      - name: Checkout branch
        uses: actions/checkout@v3
        with:
          ref: ${{ gitea.event.inputs.branch }}

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 24

      - name: Cache node_modules
        id: cache-node-modules
        uses: actions/cache@v3
        continue-on-error: true
        with:
          path: node_modules
          key: ${{ runner.os }}-node-modules-${{ hashFiles('package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-modules-

      - name: Install dependencies
        run: |
          set -euo pipefail
          if [ -d node_modules ] && [ "${{ steps.cache-node-modules.outputs.cache-hit }}" == "true" ]; then
            echo "Cache hit, verifying dependencies..."
            npm ci --prefer-offline --no-audit --silent 2>&1 | tee install.log || npm install --no-audit --silent 2>&1 | tee install.log
          else
            echo "Cache miss, installing dependencies..."
            npm ci --prefer-offline --no-audit --silent 2>&1 | tee install.log
          fi

      - name: Build (react-scripts build)
        env:
          CI: 'false'
        run: |
          set -euo pipefail
          npm run build 2>&1 | tee build.log
        timeout-minutes: 5

      - name: Save node_modules cache
        if: always()
        uses: actions/cache@v3
        continue-on-error: true
        with:
          path: node_modules
          key: ${{ runner.os }}-node-modules-${{ hashFiles('package-lock.json') }}

      - name: Verify build folder exists
        run: test -d build || (echo "No build folder. Check build logs above."; exit 1)

      - name: Upload logs (always)
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: build-logs
          path: |
            install.log
            build.log
            npm-debug.log*
          if-no-files-found: ignore

      - name: Build completed
        if: success()
        run: echo "Build completed successfully"
