name: Build (develop) / Promote (main)
on:
  push:
    branches: [main]

jobs:
  build-and-push-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Build and Push
        run: |
          set -euo pipefail
          REGISTRY="172.35.0.216:3000"
          IMAGE_NAME="$REGISTRY/simplifique/vendaweb-portal"
          SHA_TAG=$(echo "${{ github.sha }}" | cut -c1-7)

          REGISTRY_USERNAME="${{ secrets.REGISTRY_USERNAME }}"
          if [ -z "$REGISTRY_USERNAME" ]; then
            REGISTRY_USERNAME="${{ github.actor }}"
          fi

          REGISTRY_PASSWORD="${{ secrets.REGISTRY_PASSWORD }}"
          if [ -z "$REGISTRY_PASSWORD" ]; then
            REGISTRY_PASSWORD="${{ secrets.K8S }}"
          fi

          if [ -z "$REGISTRY_USERNAME" ] || [ -z "$REGISTRY_PASSWORD" ]; then
            echo "Missing registry credentials. Set secrets.REGISTRY_USERNAME + secrets.REGISTRY_PASSWORD (recommended)"
            echo "(fallback supported: secrets.K8S as password)"
            exit 1
          fi

          printf '%s' "$REGISTRY_PASSWORD" | docker login "$REGISTRY" -u "$REGISTRY_USERNAME" --password-stdin

          docker build -t "$IMAGE_NAME:$SHA_TAG" -t "$IMAGE_NAME:latest" .
          docker push "$IMAGE_NAME:$SHA_TAG"
          docker push "$IMAGE_NAME:latest"

      - name: Update Manifest and Push to Git
        run: |
          set -euo pipefail
          SHA_TAG=$(echo "${{ github.sha }}" | cut -c1-7)

          MANIFEST_FILE="k8s/overlays/prod/deployment-image-digest-patch.yaml"

          # Match image line for vendaweb-portal and replace tag (works with any registry hostname)
          sed -i -E "s|(image: .*vendaweb-portal:).*|\1${SHA_TAG}|" "$MANIFEST_FILE"

          if [ -z "${{ secrets.GITEA_TOKEN }}" ]; then
            echo "Missing secrets.GITEA_TOKEN (needed to push back to repo)"
            exit 1
          fi

          git remote set-url origin "http://${{ github.actor }}:${{ secrets.GITEA_TOKEN }}@172.35.0.216:3000/simplifique/Vendaweb-portal.git"

          git config user.name "Gitea Action"
          git config user.email "actions@simplifiquehc.com.br"

          git add "$MANIFEST_FILE"
          if git diff --staged --quiet; then
            echo "Manifest already has image tag $SHA_TAG, nothing to commit"
          else
            git commit -m "chore: update image tag to $SHA_TAG [skip ci]"
            git push origin main
          fi
