name: tests

on:
  push:
    branches:
      - develop
      - main
  pull_request:
    branches:
      - develop
      - main

jobs:
  ci:
    runs-on: ubuntu-latest
    environment: Testing

    services:
      mongo:
        image: mongo:latest
        ports:
          - 27017:27017
        options: >-
          --health-cmd="mongosh --eval 'db.runCommand({ ping: 1 })'"
          --health-interval=10s
          --health-timeout=5s
          --health-retries=3

      redis:
        image: redis:latest
        ports:
          - 6379:6379
        options: >-
          --health-cmd="redis-cli ping"
          --health-interval=10s
          --health-timeout=5s
          --health-retries=3

      mailhog:
        image: mailhog/mailhog
        ports:
          - 1025:1025
          - 8025:8025

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

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: 8.4
          tools: composer:v2
          coverage: xdebug

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'

      - name: Install Node Dependencies
        run: npm i

      - name: Add Flux Credentials Loaded From ENV
        run: composer config http-basic.composer.fluxui.dev "${{ secrets.FLUX_USERNAME }}" "${{ secrets.FLUX_LICENSE_KEY }}"

      - name: Install Dependencies
        run: composer install --no-interaction --prefer-dist --optimize-autoloader

      - name: Copy Environment File
        run: |
          cp .env.example .env
          sed -i 's/MONGODB_URI=mongodb:\/\/localhost:27017/MONGODB_URI=mongodb:\/\/127.0.0.1:27017/' .env
          sed -i 's/DB_CONNECTION=mysql/DB_CONNECTION=sqlite/' .env
          sed -i 's/MAIL_MAILER=log/MAIL_MAILER=smtp/' .env

      - name: Generate Application Key
        run: php artisan key:generate

      - name: Build Assets
        run: npm run build

      - name: Wait for services
        run: |
          until nc -z 127.0.0.1 27017; do echo "Waiting for MongoDB..."; sleep 2; done
          until nc -z 127.0.0.1 6379; do echo "Waiting for Redis..."; sleep 2; done
          until nc -z 127.0.0.1 1025; do echo "Waiting for MailHog..."; sleep 2; done

      - name: Run Tests
        run: ./vendor/bin/pest
        env:
          MAIL_HOST: 127.0.0.1
          MAIL_PORT: 1025
          REDIS_HOST: 127.0.0.1
          REDIS_PORT: 6379
          MONGODB_URI: mongodb://127.0.0.1:27017