# 自动构建 WebUI 并提交构建产物
# 触发条件：webui 目录下的文件变更

name: Build WebUI

on:
  push:
    branches:
      - main
    paths:
      - 'webui/**'
      - '.github/workflows/build-webui.yml'
  pull_request:
    branches:
      - main
    paths:
      - 'webui/**'
  # 允许手动触发
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    
    # 只在主仓库运行，避免 fork 仓库运行
    if: github.repository == 'CJackHwang/ds2api'
    
    permissions:
      contents: write
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: webui/package-lock.json
      
      - name: Install dependencies
        working-directory: webui
        run: npm ci
      
      - name: Build WebUI
        working-directory: webui
        run: npm run build
      
      - name: Check for changes
        id: check_changes
        run: |
          git add static/admin
          if git diff --staged --quiet; then
            echo "changed=false" >> $GITHUB_OUTPUT
          else
            echo "changed=true" >> $GITHUB_OUTPUT
          fi
      
      - name: Commit and push changes
        if: steps.check_changes.outputs.changed == 'true' && github.event_name == 'push'
        run: |
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          git commit -m "chore: auto-build WebUI [skip ci]"
          git push
      
      - name: Upload build artifacts (for PR review)
        if: github.event_name == 'pull_request'
        uses: actions/upload-artifact@v4
        with:
          name: webui-build
          path: static/admin
          retention-days: 7
