name: Pull Request CI-Backend

on:
  workflow_dispatch:
  pull_request:
    types: [opened, synchronize, reopened]
    branches:
      - 'main'
    paths:
      - 'server/**/*.java'
      - 'server/**/*.xml'
      - 'server/pom.xml'
      - '.github/workflows/server-ci.yml'

jobs:
  run-checks:
    name: Checks
    runs-on: ubuntu-latest
    permissions:
      contents: read

    steps:
      - name: Checkout code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

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

      - name: Run Check Style
        working-directory: ./server
        run: ./mvnw --no-transfer-progress checkstyle:check -Dcheckstyle.skip=false

      - name: Run build
        working-directory: ./server
        run: ./mvnw --no-transfer-progress clean compile -DskipTests

      - name: Run tests
        working-directory: ./server
        run: ./mvnw --no-transfer-progress clean verify -P tests --file pom.xml

  build-and-push:
    name: Build & Push
    runs-on: ubuntu-latest
    needs: ["run-checks"]
    permissions:
      contents: read
      deployments: write
      packages: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - 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 GitHub Container Registry
        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 with Spring Boot
        working-directory: ./server
        run: |
          ./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 Docker image
        run: |
          docker tag ghcr.io/${{ steps.repo.outputs.name }}/api:latest ghcr.io/${{ steps.repo.outputs.name }}/api:candidate
          docker tag ghcr.io/${{ steps.repo.outputs.name }}/api:latest ghcr.io/${{ steps.repo.outputs.name }}/api:pr-${{ github.event.pull_request.number }}
          docker push ghcr.io/${{ steps.repo.outputs.name }}/api:candidate
          docker push ghcr.io/${{ steps.repo.outputs.name }}/api:pr-${{ github.event.pull_request.number }}

      - name: Create GitHub deployment for staging
        if: ${{ github.event_name == 'pull_request' }}
        uses: actions/github-script@v6
        with:
          script: |
            const ref = context.payload.pull_request.head.sha;
            const env = 'staging';
            const resp = await github.rest.repos.createDeployment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              ref,
              required_contexts: [],
              environment: env,
              description: `PR #${context.payload.pull_request.number} preview deployment`,
              transient_environment: true,
              auto_merge: false
            });
            // create a deployment status pointing to the staging URL
            await github.rest.repos.createDeploymentStatus({
              owner: context.repo.owner,
              repo: context.repo.repo,
              deployment_id: resp.data.id,
              state: 'success',
              environment_url: 'https://tasknote-stg.darkroasted.vps-kinghost.net'
            });
