name: Build on Push and create Release on Tag

on:
  push:
    branches:
      - main
    tags:
      - "v*"

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

      # Install Node.js
      - name: Install Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 20
          registry-url: "https://registry.npmjs.org"

      # Install pnpm
      - name: Install pnpm
        uses: pnpm/action-setup@v4
        id: pnpm-install
        with:
          version: 8
          run_install: false

      # Validate Tag Matches JSON Versions
      - name: Validate Tag Matches JSON Versions
        if: github.ref_type == 'tag'
        run: |
          node scripts/validate_tag.cjs ${{ github.ref }}

      # Get pnpm store directory
      - name: Get pnpm store directory
        id: pnpm-cache
        shell: bash
        run: |
          echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT

      # Setup pnpm cache
      - name: Setup pnpm cache
        uses: actions/cache@v3
        with:
          path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-store-

      # Install dependencies
      - name: Install dependencies
        run: pnpm install

      # Build for production, 这一步会生成一个 package.zip
      - name: Build for production
        run: pnpm build

      # Move file
      - name: Move file
        run: mkdir built; mv package.zip built/package.zip

      # Upload artifacts
      - name: Upload artifacts
        uses: actions/upload-artifact@v3
        with:
          path: built/package.zip
          overwrite: true

      # Create Forgejo Release
      - name: Create Forgejo Release
        if: github.ref_type == 'tag'
        uses: actions/forgejo-release@v1
        with:
          direction: upload
          release-dir: built
          token: ${{ secrets.FORGE_TOKEN }}
