name: Build and Push Server

# This workflow runs on every push to the main branch.
on:
  push:
    branches:
      - main

jobs:
  build-and-push:
    # The job runs on a standard Ubuntu runner.
    runs-on: ubuntu-latest

    steps:
      # Step 1: Check out the repository code.
      - name: Checkout repository
        uses: actions/checkout@v4

      # Step 2: Set up the Node.js environment for building the SvelteKit playground.
      - name: Setup Mise
        uses: jdx/mise-action@v3

      # Step 3: Set up pnpm, which is used for dependency management in the playground.
      - name: Set up pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 9

      - uses: acifani/setup-tinygo@v2
        with:
          tinygo-version: '0.37.0'

      # Step 4: Install the playground's dependencies.
      - name: Install playground dependencies
        working-directory: ./playground
        run: pnpm install --frozen-lockfile

      - name: Build marka wasm
        working-directory: ./playground
        run: ./wasm/build.sh

      # Step 5: Build the SvelteKit playground to generate static assets.
      - name: Build playground
        working-directory: ./playground
        run: pnpm build

      # Step 6: The Dockerfile expects the built playground assets in './server/playground'.
      # This step moves the build output from './playground/build' to the correct location.
      - name: Move playground build to server context
        run: |
          echo "Moving playground build output..."
          rm -rf ./server/playground
          mv ./playground/build ./server/playground
          echo "Move complete."

      - name: Set up Docker BuildX
        uses: docker/setup-buildx-action@v2
        with: # replace it with your local IP
          config-inline: |
            [registry."git.max-richter.dev"] 
              https = true
              insecure = false

      # Step 7: Log in to the Gitea container registry.
      # You need to create a repository secret named GITEA_TOKEN with an access token.
      - name: Login to Gitea Registry
        uses: docker/login-action@v3
        with:
          registry: git.max-richter.dev
          username: ${{ gitea.actor }}
          password: ${{ secrets.REGISTRY_TOKEN }}

      # Step 8: Build the Docker image and push it to the Gitea registry.
      # The image is tagged with 'latest' and the short commit SHA.
      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./server/Dockerfile
          push: true
          tags: |
            git.max-richter.dev/${{ gitea.repository }}:latest
            git.max-richter.dev/${{ gitea.repository }}:${{ gitea.sha }}
          build-args: |
            GIT_COMMIT=${{ gitea.sha }}
