name: Build and Publish Docker Image

on:
  push:
    branches:
      - master

env:
  REGISTRY: 192.168.10.174:3000
  IMAGE_NAME: ${{ gitea.repository }}

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Compute version and image names
        run: |
          LOWERCASE_IMAGE=$(echo "${{ env.IMAGE_NAME }}" | tr '[:upper:]' '[:lower:]')
          # Version sémantique lue dans package.json (sans dépendre de node)
          VERSION=$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' package.json | head -1)
          [ -z "$VERSION" ] && VERSION="0.0.0"
          BUILD="${{ gitea.run_number }}"
          SHORT_SHA=$(echo "${{ gitea.sha }}" | cut -c1-7)
          {
            echo "FRONT=${{ env.REGISTRY }}/$LOWERCASE_IMAGE"
            echo "BACK=${{ env.REGISTRY }}/$LOWERCASE_IMAGE-backend"
            echo "VERSION=$VERSION"
            echo "TAG=$VERSION-$BUILD"
            echo "SHORT_SHA=$SHORT_SHA"
          } >> "$GITHUB_ENV"
          echo "Publication version $VERSION (build $BUILD, commit $SHORT_SHA)"

      - name: Log in to the Container registry
        run: echo "${{ secrets.DOCKER_TOKEN }}" | docker login ${{ env.REGISTRY }} -u "${{ gitea.actor }}" --password-stdin

      # Frontend image (nginx + SPA)
      - name: Build frontend Docker image
        run: |
          docker build \
            -t "$FRONT:latest" \
            -t "$FRONT:$VERSION" \
            -t "$FRONT:$TAG" \
            -t "$FRONT:$SHORT_SHA" \
            .

      - name: Push frontend Docker image
        run: |
          docker push "$FRONT:latest"
          docker push "$FRONT:$VERSION"
          docker push "$FRONT:$TAG"
          docker push "$FRONT:$SHORT_SHA"

      # Backend image (Express API)
      - name: Build backend Docker image
        run: |
          docker build \
            -t "$BACK:latest" \
            -t "$BACK:$VERSION" \
            -t "$BACK:$TAG" \
            -t "$BACK:$SHORT_SHA" \
            ./server

      - name: Push backend Docker image
        run: |
          docker push "$BACK:latest"
          docker push "$BACK:$VERSION"
          docker push "$BACK:$TAG"
          docker push "$BACK:$SHORT_SHA"
