name: Build & Push Docker image

on:
  push:
    branches: [main]
    tags: ["v*"]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Set up .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: "10.0.x"
      - name: Build
        run: dotnet build -c Release
      - name: Test
        run: dotnet test -c Release --no-build

  docker:
    needs: test
    runs-on: ubuntu-latest
    # GITEA_TOKEN is auto-provided per run; grant it permission to push to the registry.
    permissions:
      packages: write
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      # Registry host defaults to this Gitea instance; the image is named after the repo.
      - name: Resolve image metadata
        id: meta
        run: |
          REGISTRY="${GITHUB_SERVER_URL#https://}"
          REGISTRY="${REGISTRY#http://}"
          echo "registry=${REGISTRY}" >> "$GITHUB_OUTPUT"
          echo "image=${REGISTRY}/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT"
          if [ "${GITHUB_REF_TYPE}" = "tag" ]; then
            echo "tag=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
          else
            echo "tag=latest" >> "$GITHUB_OUTPUT"
          fi

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

      - name: Log in to Gitea container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ steps.meta.outputs.registry }}
          username: ${{ github.actor }}
          password: ${{ secrets.REGISTRY_TOKEN }}

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: |
            ${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.tag }}
            ${{ steps.meta.outputs.image }}:${{ github.sha }}
