image: php:8.2

pipelines:
  branches:
    # ---------------------------------------------------------
    # Staging
    # ---------------------------------------------------------
    staging:
      - step:
          name: 🧪 Test Backend (Laravel)
          caches:
            - composer
          services:
            - mysql
          script:
            - apt-get update && apt-get install -y unzip git libpng-dev libzip-dev libxslt1-dev libicu-dev default-mysql-client
            - docker-php-ext-install pdo_mysql gd zip xsl bcmath intl
            - curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
            - cp .env.example .env
            - sed -i 's/DB_HOST=database/DB_HOST=127.0.0.1/' .env
            - sed -i 's/DB_DATABASE=laravel/DB_DATABASE=test_db/' .env
            - sed -i 's/DB_USERNAME=laravel/DB_USERNAME=root/' .env
            - sed -i 's/DB_PASSWORD=laravel/DB_PASSWORD=password/' .env
            - COMPOSER_ALLOW_SUPERUSER=1 composer install --no-interaction --prefer-dist
            - php artisan key:generate
            - php artisan test

      - step:
          name: 🚀 Deploy to Staging
          deployment: staging
          script:
            - pipe: atlassian/ssh-run:0.8.0
              variables:
                SSH_USER: $STAGING_USER
                SERVER: $STAGING_HOST
                PORT: $STAGING_PORT
                COMMAND: |
                  set -e
                  cd /var/www/html

                  echo "📥 Pulling latest changes..."
                  git pull origin staging

                  echo "📦 Installing dependencies..."
                  composer install --no-dev --optimize-autoloader

                  echo "🗃️ Running migrations..."
                  php artisan migrate --force
                  php artisan migrate --path="/database/migrations/project" --force

                  echo "🧹 Clearing cache..."
                  php artisan config:clear
                  php artisan route:clear
                  php artisan view:clear
                  php artisan cache:clear

                  echo "✅ Staging deployment completed!"

definitions:
  caches:
    composer: ~/.composer/cache
  services:
    mysql:
      image: mysql:8.0
      variables:
        MYSQL_DATABASE: test_db
        MYSQL_ROOT_PASSWORD: password
