name: Build Server Candidate

on:
  workflow_dispatch:

jobs:
  build-and-push-server:
    name: Build & Push Server
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ github.ref }}

      - name: Set lowercase repo name
        id: repo
        run: echo "name=${GITHUB_REPOSITORY,,}" >> $GITHUB_OUTPUT

      - name: Set up Java
        uses: actions/setup-java@v4
        with:
          distribution: 'temurin'
          java-version: '25'
          cache: 'maven'
          cache-dependency-path: 'server/pom.xml'

      - name: Log in to GHCR
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Cache Buildpack layers
        uses: actions/cache@v4
        with:
          path: ~/.cache/reproducible-builds
          key: ${{ runner.os }}-buildpack-${{ hashFiles('server/pom.xml') }}
          restore-keys: |
            ${{ runner.os }}-buildpack-
  
      - name: Build Docker image
        working-directory: ./server
        run: |
          # Use the dynamic repo name to prevent tagging errors
          ./mvnw -Pnative -DskipTests spring-boot:build-image \
            -Dspring-boot.build-image.imageName=ghcr.io/${{ steps.repo.outputs.name }}/api:latest \
            -Dspring-boot.build-image.builder=paketobuildpacks/builder-jammy-tiny:latest

      - name: Tag and push candidate
        run: |
          docker tag ghcr.io/${{ steps.repo.outputs.name }}/api:latest ghcr.io/${{ steps.repo.outputs.name }}/api:candidate
          docker push ghcr.io/${{ steps.repo.outputs.name }}/api:candidate
