name: CI

on:
  push:
    branches: [main]
  pull_request:

jobs:
  test-build-push:
    runs-on: golang
    container:
      image: golang:1.26
    env:
      GOPRIVATE: forgejo.riotpiao.com
      REGISTRY: forgejo.riotpiao.com
      IMAGE: forgejo.riotpiao.com/rock/poimen-workflows
    steps:
      - name: Configure git authentication
        run: |
          git config --global url."https://oauth2:${{ secrets.REGISTRY_PAT }}@forgejo.riotpiao.com".insteadOf "https://forgejo.riotpiao.com"
          git config --global credential.helper store
          echo "https://oauth2:${{ secrets.REGISTRY_PAT }}@forgejo.riotpiao.com" >> ~/.git-credentials

      - name: Checkout code
        run: |
          git init
          git remote add origin https://forgejo.riotpiao.com/rock/poimen-workflows.git
          git fetch origin ${{ github.head_ref || github.ref_name }} --depth=1
          git checkout FETCH_HEAD

      - name: Download dependencies
        run: go mod download

      - name: Vet
        run: go vet ./...

      - name: Test
        run: go test ./...

      - name: Build binary
        run: CGO_ENABLED=0 GOOS=linux go build -o /tmp/poimen-worker ./cmd/worker

      - name: Get short SHA
        id: sha
        run: echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT

      - name: Registry login
        if: github.ref == 'refs/heads/main' && github.event_name == 'push'
        run: |
          echo "${{ secrets.FORGEJO_REGISTRY_TOKEN }}" | docker login "${REGISTRY}" \
            --username "${{ secrets.FORGEJO_REGISTRY_USER }}" --password-stdin

      - name: Build and push image
        if: github.ref == 'refs/heads/main' && github.event_name == 'push'
        run: |
          docker build \
            -t "${IMAGE}:${{ steps.sha.outputs.short_sha }}" \
            -t "${IMAGE}:latest" \
            .
          docker push "${IMAGE}:${{ steps.sha.outputs.short_sha }}"
          docker push "${IMAGE}:latest"
          echo "✓ Pushed ${IMAGE}:${{ steps.sha.outputs.short_sha }}"
