name: Build & Deploy Marketplace API

on:
  push:
    paths: ['core/marketplace-api/**']
    branches: [main]
  workflow_dispatch:

env:
  REGISTRY: ghcr.io
  IMAGE: ghcr.io/openova-io/openova/marketplace-api

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    outputs:
      sha_short: ${{ steps.vars.outputs.sha_short }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set short SHA
        id: vars
        run: echo "sha_short=$(echo $GITHUB_SHA | head -c 7)" >> "$GITHUB_OUTPUT"

      - name: Login to GHCR
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: core/marketplace-api
          file: core/marketplace-api/Containerfile
          push: true
          tags: |
            ${{ env.IMAGE }}:${{ steps.vars.outputs.sha_short }}
            ${{ env.IMAGE }}:latest

  deploy:
    needs: [build]
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Update deployment manifest with new SHA tag
        env:
          SHA_SHORT: ${{ needs.build.outputs.sha_short }}
        run: |
          DEPLOY_DIR="products/catalyst/chart/templates/marketplace-api"
          sed -i "s|image: ${IMAGE}:.*|image: ${IMAGE}:${SHA_SHORT}|" \
            "${DEPLOY_DIR}/deployment.yaml"
          echo "Updated manifest to SHA ${SHA_SHORT}:"
          grep "image:" "${DEPLOY_DIR}/deployment.yaml"

      - name: Commit and push manifest updates
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add products/
          git diff --staged --quiet && echo "No changes to commit" && exit 0
          git commit -m "deploy: update Catalyst marketplace-api image to ${SHA_SHORT}"
          git push
        env:
          SHA_SHORT: ${{ needs.build.outputs.sha_short }}
