# ============================================================
# ESTAIR Connect CHAPS - Bitbucket Pipelines
# Tests + Deploiement Staging
# ============================================================

image: php:8.2-cli

definitions:
  caches:
    composer:
      key:
        files:
          - composer.lock
      path: vendor

  services:
    mysql:
      image: mysql:8.0
      environment:
        MYSQL_ROOT_PASSWORD: root
        MYSQL_DATABASE: ceterisprime_chaps
        MYSQL_USER: ceterisprime_connect
        MYSQL_PASSWORD: testing@2025

  steps:
    - step: &test-step
        name: Tests PHPUnit
        caches:
          - composer
        services:
          - mysql
        script:
          - apt-get update && apt-get install -y unzip libzip-dev libpng-dev
          - docker-php-ext-install zip pdo_mysql bcmath gd
          - curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
          - composer install --prefer-dist --no-progress

          # Attente MySQL
          - |
            for i in $(seq 1 30); do
              if php -r "try { new PDO('mysql:host=127.0.0.1;dbname=ceterisprime_chaps', 'ceterisprime_connect', 'testing@2025'); echo 'ok'; exit(0); } catch(Exception \$e) { exit(1); }"; then
                echo "MySQL pret"
                break
              fi
              echo "Attente MySQL... ($i/30)"
              sleep 2
            done

          # Configuration
          - cp .env.example .env
          - echo "APP_ENV=testing" >> .env
          - echo "DB_CONNECTION=mysql" >> .env
          - echo "DB_HOST=127.0.0.1" >> .env
          - echo "DB_PORT=3306" >> .env
          - echo "DB_DATABASE=ceterisprime_chaps" >> .env
          - echo "DB_USERNAME=ceterisprime_connect" >> .env
          - echo "DB_PASSWORD=testing@2025" >> .env
          - echo "OTEL_SDK_DISABLED=true" >> .env
          - php artisan key:generate

          # Migrations + Tests
          - php artisan migrate --force
          - php artisan test
        artifacts:
          - storage/logs/**

    - step: &create-pr-step
        name: Create PR dev → master
        image: alpine:3.19
        script:
          - apk add --no-cache curl
          - |
            echo "Creation PR dev -> master..."
            HTTP_CODE=$(curl -s -o /tmp/pr_response.txt -w "%{http_code}" \
              -X POST \
              -u "nicephore.allaglo@jupitech.fr:$BB_APP_PASSWORD" \
              -H "Content-Type: application/json" \
              "https://api.bitbucket.org/2.0/repositories/$BITBUCKET_REPO_FULL_NAME/pullrequests" \
              -d '{
                "title": "Merge dev (build #'"$BITBUCKET_BUILD_NUMBER"')",
                "source": {"branch": {"name": "dev"}},
                "destination": {"branch": {"name": "master"}},
                "description": "PR auto-generee apres succes des tests (pipeline #'"$BITBUCKET_BUILD_NUMBER"').\n\nCommit: '"$BITBUCKET_COMMIT"'",
                "close_source_branch": false
              }')
            if [ "$HTTP_CODE" = "201" ]; then
              echo "PR creee avec succes"
            elif [ "$HTTP_CODE" = "409" ]; then
              echo "PR deja existante - rien a faire"
            else
              echo "Erreur creation PR (HTTP $HTTP_CODE):"
              cat /tmp/pr_response.txt
              exit 1
            fi

    - step: &deploy-staging-step
        name: Deploy to Staging
        deployment: staging
        script:
          - apt-get update && apt-get install -y openssh-client
          - mkdir -p ~/.ssh
          - echo "$STAGING_SSH_KEY" | base64 -d > ~/.ssh/id_rsa
          - chmod 600 ~/.ssh/id_rsa
          - ssh-keyscan -H $STAGING_SERVER_IP >> ~/.ssh/known_hosts
          # Upload deploy script then execute
          - scp -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no deploy-staging.sh $STAGING_SSH_USER@$STAGING_SERVER_IP:$STAGING_DEPLOY_ROOT/deploy-chaps.sh
          - ssh -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no $STAGING_SSH_USER@$STAGING_SERVER_IP "export GIT_USER=jupitechfr && export GIT_TOKEN='$BB_APP_PASSWORD' && bash $STAGING_DEPLOY_ROOT/deploy-chaps.sh"

pipelines:
  default:
    - step: *test-step

  branches:
    dev:
      # - step: *test-step
      - step: *create-pr-step
    master:
      - step: *deploy-staging-step

  custom:
    daily-tests:
      - step: *test-step
