name: Build Chrome Extension

on:
  push:
    branches: [ "main" ]
    tags: [ "ext-v*" ]
    paths:
      - 'extension/**'
      - '.github/workflows/build-extension.yml'
  pull_request:
    branches: [ "main" ]
    paths:
      - 'extension/**'
      - '.github/workflows/build-extension.yml'

permissions:
  contents: write

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Code
        uses: actions/checkout@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 22
          cache: 'npm'
          cache-dependency-path: extension/package-lock.json

      - name: Install extension dependencies
        run: npm ci
        working-directory: extension

      - name: Build extension
        run: npm run build
        working-directory: extension

      - name: Prepare extension package
        run: npm run package:release -- --out ../extension-package
        working-directory: extension

      - name: Create Extension ZIP
        run: |
          EXT_VERSION=$(node -p "require('./extension/package.json').version")
          cd extension-package
          zip -r ../opencli-extension-v${EXT_VERSION}.zip .

      - name: Upload Artifacts (Action Run)
        uses: actions/upload-artifact@v7
        with:
          name: opencli-extension-build
          path: opencli-extension-v*.zip
          retention-days: 7

      - name: Attach to GitHub Release
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v3.0.0
        with:
          files: opencli-extension-v*.zip
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
