name: Release package

on:
  push:
    branches:
      - main
      - dev-*

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Set up JDK
        uses: actions/setup-java@v5
        with:
          distribution: "temurin"
          java-version: "25"

      - name: Log in to Gitea Container Registry
        uses: docker/login-action@v3
        with:
          registry: git.demonkernel.io.vn
          username: ${{ github.actor }}
          password: ${{ secrets.ACCESS_TOKEN }}

      - uses: actions/setup-node@v6
        with:
          node-version: latest

      - uses: pnpm/action-setup@v3
        with:
          version: latest
          run_install: false

      - name: Get pnpm store directory
        shell: bash
        run: |
          echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV

      - name: Cache Maven packages
        uses: actions/cache@v3
        with:
          path: ~/.m2/repository
          key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
          restore-keys: |
            ${{ runner.os }}-maven-

      - uses: actions/cache@v3
        name: Setup pnpm cache
        with:
          path: ${{ env.STORE_PATH }}
          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/package.json') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-store-

      - name: Run Semantic Release
        env:
          GITEA_USER: ${{ github.actor }}
          GITEA_TOKEN: ${{ secrets.ACCESS_TOKEN }}
        run: |
          pnpm i
          pnpm format
          pnpm release

      - name: Commit & Push Changes
        env:
          MY_PAT_TOKEN: ${{ secrets.ACCESS_TOKEN }}
        run: |
          if [ -n "$(git status --porcelain)" ]; then
            git config --global user.name "gitea-actions"
            git config --global user.email "actions-user@noreply.git.demonkernel.io.vn"

            git remote set-url origin https://x-access-token:${MY_PAT_TOKEN}@git.demonkernel.io.vn/${{ github.repository }}.git

            git add .
            git commit -m "chore: release [ci skip]"
            
            git push origin HEAD:${{ github.ref_name }}
          fi
