name: Build & Deploy OSEP

on:
  push:
    branches:
      - main
      - master
      - feature/osep-rebrand
    tags:
      - 'v*'
    paths-ignore:
      - '**.md'
      - 'docs/**'
      - '.gitignore'

  workflow_dispatch:
    inputs:
      deploy:
        type: boolean
        description: "Déployer après le build ?"
        default: true
      tag_override:
        type: string
        description: "Tag d'image à utiliser (laisser vide = auto)"
        default: ''
      no_cache:
        type: boolean
        description: "Forcer le rebuild sans cache BuildKit (résout les bundles SCSS stale)"
        default: true

# Une seule pipeline de déploiement à la fois (évite les races sur le serveur)
concurrency:
  group: deploy-${{ github.ref }}
  cancel-in-progress: false

env:
  REGISTRY: docker.io
  IMAGE_NAME: massambafall92/kplan-www
  DOCKERFILE_PATH: docker/stack/php/Dockerfile

jobs:
  # ===========================================================================
  # 1) Build & push de l'image Docker
  # ===========================================================================
  build:
    name: Build & Push Image
    runs-on: ubuntu-latest

    outputs:
      image_tag: ${{ steps.version.outputs.tag }}
      image_full: ${{ steps.version.outputs.full }}

    steps:
      - name: Checkout du code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Génération du tag de version
        id: version
        run: |
          # Format: YYYYMMDDHHMM-<sha7>  (compatible avec la convention existante)
          if [ -n "${{ github.event.inputs.tag_override }}" ]; then
            TAG="${{ github.event.inputs.tag_override }}"
          else
            TAG="$(date +%Y%m%d%H%M)-$(git rev-parse --short=7 HEAD)"
          fi
          echo "tag=$TAG" >> $GITHUB_OUTPUT
          echo "full=${{ env.IMAGE_NAME }}:$TAG" >> $GITHUB_OUTPUT
          echo "→ Image qui sera produite : ${{ env.IMAGE_NAME }}:$TAG"

      - name: Setup Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Login Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Build & push de l'image
        id: build
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ${{ env.DOCKERFILE_PATH }}
          push: true
          tags: |
            ${{ env.IMAGE_NAME }}:${{ steps.version.outputs.tag }}
            ${{ env.IMAGE_NAME }}:latest
          # Si no_cache=true (workflow_dispatch), on saute le cache pour produire un build 100 % frais.
          cache-from: ${{ github.event.inputs.no_cache == 'true' && '' || 'type=gha' }}
          cache-to: ${{ github.event.inputs.no_cache == 'true' && '' || 'type=gha,mode=max' }}
          no-cache: ${{ github.event.inputs.no_cache == 'true' }}
          platforms: linux/amd64
          provenance: false

      - name: Vérification du build des assets dans l'image
        run: |
          echo "→ Vérification que public/build/ contient bien les CSS OSEP"
          docker run --rm --entrypoint sh \
            ${{ steps.version.outputs.full }} \
            -c '
              set -e
              if [ ! -d /var/www/public/build ]; then
                echo "::error::/var/www/public/build/ ABSENT de l image"
                exit 1
              fi
              ls -la /var/www/public/build/ | head -10

              APP_CSS=$(find /var/www/public/build -name "app.*.css" | head -1)
              if [ -z "$APP_CSS" ]; then
                echo "::error::Aucun app.*.css trouvé dans /var/www/public/build/"
                exit 1
              fi

              if ! grep -q "osep-" "$APP_CSS"; then
                echo "::error::Classes osep- absentes du bundle CSS — le SCSS OSEP n est pas inclus"
                exit 1
              fi

              COUNT=$(grep -c "osep-" "$APP_CSS" || true)
              echo "✓ $COUNT occurrences de osep- trouvées dans $APP_CSS"
            '

      - name: Récap du build
        if: always()
        run: |
          echo "## 📦 Build OSEP" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "| Champ | Valeur |" >> $GITHUB_STEP_SUMMARY
          echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
          echo "| Image | \`${{ steps.version.outputs.full }}\` |" >> $GITHUB_STEP_SUMMARY
          echo "| Tag | \`${{ steps.version.outputs.tag }}\` |" >> $GITHUB_STEP_SUMMARY
          echo "| Commit | \`${{ github.sha }}\` |" >> $GITHUB_STEP_SUMMARY
          echo "| Branche | \`${{ github.ref_name }}\` |" >> $GITHUB_STEP_SUMMARY
          echo "| Auteur | @${{ github.actor }} |" >> $GITHUB_STEP_SUMMARY
