name: Build and Push Medusa

on:
  push:
    branches:
      - main
    paths:
      - 'workloads/commerce-backend/**'
      - '.gitea/workflows/build-medusa.yaml'

permissions:
  contents: write
  packages: write

jobs:
  build:
    name: Construir y publicar Medusa
    runs-on: ubuntu-latest
    timeout-minutes: 45

    steps:
      - name: Checkout del código
        uses: actions/checkout@v3
        with:
          fetch-depth: 1
          persist-credentials: true

      - name: Definir versión
        id: vars
        shell: bash
        run: |
          set -euo pipefail
          echo "VERSION=v1.0.${{ github.run_number }}" >> "$GITHUB_OUTPUT"

      - name: Validar secretos del Registry
        shell: bash
        env:
          REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
          REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
        run: |
          set -euo pipefail
          test -n "${REGISTRY_USER}" || {
            echo "ERROR: REGISTRY_USER no está configurado."
            exit 1
          }
          test -n "${REGISTRY_PASSWORD}" || {
            echo "ERROR: REGISTRY_PASSWORD no está configurado."
            exit 1
          }

      - name: Login en Gitea Registry
        uses: docker/login-action@v2
        with:
          registry: gitea.cruzcloud.net
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_PASSWORD }}
          logout: true

      - name: Construir y subir imagen
        uses: docker/build-push-action@v4
        with:
          context: workloads/commerce-backend/
          file: workloads/commerce-backend/Dockerfile
          push: true
          tags: |
            gitea.cruzcloud.net/devops/ecommerce-medusa:${{ steps.vars.outputs.VERSION }}
            gitea.cruzcloud.net/devops/ecommerce-medusa:latest

      - name: Verificar promoción segura
        id: promotion
        shell: bash
        run: |
          set -euo pipefail

          git fetch origin main

          CURRENT_SHA="${{ github.sha }}"
          REMOTE_SHA="$(git rev-parse origin/main)"

          if [ "${CURRENT_SHA}" = "${REMOTE_SHA}" ]; then
            echo "promote=true" >> "$GITHUB_OUTPUT"
          else
            echo "promote=false" >> "$GITHUB_OUTPUT"
            echo "Hay un commit más reciente; no se actualizará el manifiesto."
          fi

      - name: Actualizar manifiesto Medusa
        if: steps.promotion.outputs.promote == 'true'
        shell: bash
        run: |
          set -euo pipefail

          VERSION="${{ steps.vars.outputs.VERSION }}"
          MANIFEST="workloads/ecommerce/commerce/medusa.yaml"
          IMAGE="gitea.cruzcloud.net/devops/ecommerce-medusa"

          git config user.name "gitea-actions"
          git config user.email "gitea-actions@cruzcloud.net"

          git fetch origin main
          git checkout -B main origin/main

          sed -i -E \
            "s|(${IMAGE}:)v[0-9]+\.[0-9]+\.[0-9]+|\1${VERSION}|g" \
            "${MANIFEST}"

          git add "${MANIFEST}"

          if git diff --cached --quiet; then
            echo "El manifiesto ya apunta a ${VERSION}."
            exit 0
          fi

          git commit \
            -m "chore(gitops): deploy Medusa ${VERSION} [skip ci]"

          git push origin HEAD:main
