name: Laravel CI-CD (Gitea)

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  test:
    name: "Tests Unitaires"
    runs-on: ubuntu-latest
    container:
      image: laravelsail/php84-composer:latest
    env:
      APP_ENV: testing
      APP_KEY: base64:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
      DB_CONNECTION: sqlite
      DB_DATABASE: ":memory:"
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Install dependencies
        run: |
          apt-get update && apt-get install -y libicu-dev
          docker-php-ext-configure intl && docker-php-ext-install intl
          composer install --no-interaction --prefer-dist

      - name: Run Tests
        run: php artisan test

  build:
    name: "Build & Push Docker"
    needs: test
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Login to Gitea Registry
        uses: actions/docker/login@v2
        with:
          # Remplacez par l'URL de votre registry Gitea (ex: gitea.votre-domaine.com)
          registry: ${{ github.server_url }} 
          username: ${{ github.actor }}
          password: ${{ secrets.GITEA_TOKEN }}

      - name: Build and Push
        run: |
          IMAGE_NAME="${{ github.repository }}" # Format: user/repo
          REGISTRY_URL=$(echo "${{ github.server_url }}" | sed -e 's|https://||')
          FULL_IMAGE_NAME="$REGISTRY_URL/$IMAGE_NAME"
          
          docker build -t "$FULL_IMAGE_NAME:${{ github.sha }}" -t "$FULL_IMAGE_NAME:latest" .
          docker push "$FULL_IMAGE_NAME:${{ github.sha }}"
          docker push "$FULL_IMAGE_NAME:latest"

  deploy:
    name: "Déploiement Portainer"
    needs: build
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    container:
      image: alpine:latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Install Tools
        run: apk add --no-cache curl jq gettext

      - name: Render Docker Compose
        env:
          # Mappez ici vos variables pour envsubst
          IMAGE_TAG: ${{ github.sha }}
        run: envsubst < docker-compose.prod.yml > docker-compose.rendered.yml

      - name: Deploy to Portainer
        env:
          PORTAINER_URL: ${{ secrets.PORTAINER_URL }}
          PORTAINER_API_KEY: ${{ secrets.PORTAINER_API_KEY }}
          PORTAINER_ENDPOINT_ID: ${{ secrets.PORTAINER_ENDPOINT_ID }}
          PORTAINER_STACK_NAME: ${{ secrets.PORTAINER_STACK_NAME }}
        run: |
          set -eu
          PORTAINER_BASE_URL="${PORTAINER_URL%/}"
          STACK_FILE_PATH="docker-compose.rendered.yml"

          # Le script reste identique au vôtre pour la logique cURL...
          STACKS_RESPONSE=$(curl -sS -H "X-API-Key: $PORTAINER_API_KEY" "$PORTAINER_BASE_URL/api/stacks")
          STACK_ID=$(echo "$STACKS_RESPONSE" | jq -r ".[] | select(.Name == \"$PORTAINER_STACK_NAME\") | .Id")

          if [ -z "$STACK_ID" ]; then
            echo "Creating new stack..."
            JSON_PAYLOAD=$(jq -n --arg name "$PORTAINER_STACK_NAME" --rawfile content "$STACK_FILE_PATH" '{name: $name, stackFileContent: $content, prune: true, fromAppTemplate: false}')
            curl -sS -X POST "$PORTAINER_BASE_URL/api/stacks/create/standalone/string?endpointId=$PORTAINER_ENDPOINT_ID" \
              -H "X-API-Key: $PORTAINER_API_KEY" -H "Content-Type: application/json" --data "$JSON_PAYLOAD"
          else
            echo "Updating existing stack $STACK_ID..."
            JSON_PAYLOAD=$(jq -n --arg id "$STACK_ID" --rawfile content "$STACK_FILE_PATH" '{id: ($id|tonumber), stackFileContent: $content, prune: false, pullImage: true}')
            curl -sS -X PUT "$PORTAINER_BASE_URL/api/stacks/$STACK_ID?endpointId=$PORTAINER_ENDPOINT_ID&method=string" \
              -H "X-API-Key: $PORTAINER_API_KEY" -H "Content-Type: application/json" --data "$JSON_PAYLOAD"
          fi
