name: Backend CI/CD

on:
  push:
    tags:
      - "v[0-9]+.[0-9]+.[0-9]+*"
    paths:
      - 'backend/**'
      - '.github/workflows/backend-ci-cd.yml'
  pull_request:
    branches:
      - main
    paths:
      - 'backend/**'
      - '.github/workflows/backend-ci-cd.yml'

env:
  REGISTRY: chaitin-registry.cn-hangzhou.cr.aliyuncs.com/monkeycode

jobs:
  test:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: ./backend
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Go
        uses: actions/setup-go@v4
        with:
          go-version: '1.23'

      - name: Cache Go modules
        uses: actions/cache@v4
        with:
          path: |
            ~/.cache/go-build
            ~/go/pkg/mod
          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
          restore-keys: |
            ${{ runner.os }}-go-

      - name: Download dependencies
        run: go mod download

      - name: Run tests
        run: go test -v ./...

      - name: Validate go.mod and go.sum
        run: |
          go mod tidy
          go mod verify
          if [ -n "$(git status --porcelain)" ]; then
            echo "go.mod or go.sum files are not up to date"
            git diff
            exit 1
          fi

  build:
    needs: test
    runs-on: ubuntu-latest
    if: github.event_name != 'pull_request'
    defaults:
      run:
        working-directory: ./backend
    outputs:
      version: ${{ steps.get_version.outputs.VERSION }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Get version
        id: get_version
        run: |
          VERSION=${GITHUB_REF#refs/tags/}
          echo "VERSION=${VERSION}" >> $GITHUB_OUTPUT

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Login to Aliyun Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.CT_ALIYUN_USER }}
          password: ${{ secrets.CT_ALIYUN_PASS }}

      - name: Build and push backend image
        uses: docker/build-push-action@v5
        with:
          context: ./backend
          file: ./backend/build/Dockerfile
          push: true
          platforms: linux/amd64, linux/arm64
          tags: |
            ${{ env.REGISTRY }}/backend:${{ steps.get_version.outputs.VERSION }}
            ${{ env.REGISTRY }}/backend:latest
          build-args: |
            GOCACHE=/tmp/go-build
            GOMODCACHE=/tmp/go-mod
            REPO_COMMIT=${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max