name: Laravel CI

on:
  push:
    branches: [ "main" ]

jobs:
  laravel-tests:
    runs-on: ubuntu-latest

    services:
      mysql:
        image: mysql:5.7
        env:
          MYSQL_ROOT_PASSWORD: root
          MYSQL_DATABASE: laravel_test
        ports:
          - 3306:3306
        options: >-
          --health-cmd="mysqladmin ping -h127.0.0.1 -uroot -proot --silent"
          --health-interval=10s
          --health-timeout=5s
          --health-retries=5

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

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.1'
          extensions: mbstring, bcmath, pdo, pdo_mysql, xml, ctype, json, tokenizer, gd
          coverage: none

      - name: Cache Composer packages
        uses: actions/cache@v3
        with:
          path: vendor
          key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
          restore-keys: |
            ${{ runner.os }}-php-

      - name: Install Composer dependencies
        run: composer install --prefer-dist --no-progress --optimize-autoloader

      # Setup dedicated testing environment
      - name: Setup .env.testing
        run: |
          cp .env.example .env.testing
          echo "APP_ENV=testing" >> .env.testing
          echo "DB_CONNECTION=mysql" >> .env.testing
          echo "DB_HOST=127.0.0.1" >> .env.testing
          echo "DB_PORT=3306" >> .env.testing
          echo "DB_DATABASE=laravel_test" >> .env.testing
          echo "DB_USERNAME=root" >> .env.testing
          echo "DB_PASSWORD=root" >> .env.testing
          php artisan key:generate --env=testing

      # Wait for MySQL to be ready
      - name: Wait for MySQL
        run: |
          sudo apt-get update
          sudo apt-get install -y mysql-client
          echo "Waiting for MySQL to be ready..."
          until mysql -h127.0.0.1 -uroot -proot -e "SELECT 1;" >/dev/null 2>&1; do
            sleep 2
            echo "Still waiting for MySQL..."
          done
          echo "MySQL is ready!"

      # Run migrations using testing env
      - name: Run migrations
        run: php artisan migrate --force --env=testing

      # Run backend tests using testing env
      - name: Run Tests
        run: php artisan test --env=testing

      # Optional: frontend build if using Laravel Mix or Vite
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20'

      - name: Install Node dependencies
        run: npm install

      - name: Build frontend assets
        run: npm run build