name: Continuous Integration that check code quality both on front and back application

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

jobs:
  build-and-test-front-end:
    name: 'Front-end CI'
    runs-on: ubuntu-latest
    timeout-minutes: 15

    strategy:
      matrix:
        node-version: [20.x]

    steps:

      - name: Checkout front-end code
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node-version }}

      - name: Install front-end dependencies
        working-directory: ./client
        run: npm install

      - name: Build front-end code
        working-directory: ./client
        run: npm run build

      - name: Lint front-end
        working-directory: ./client
        run: npm run lint
    
  build-and-test-back-end:
    name: 'Back-end CI'
    runs-on: ubuntu-latest
    timeout-minutes: 15

    services:
      mysql:
        image: mysql:latest
        env:
          MYSQL_ROOT_PASSWORD: admin
          MYSQL_DATABASE: testing
        ports:
          - 3306:3306
        options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3

    steps:

      - name: Checkout back-end code
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Set up PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'

      - name: update back-end dependencies
        working-directory: ./server
        run: composer update

      - name: Install back-end dependencies
        working-directory: ./server
        run: composer install

      - name: Lint back-end
        working-directory: ./server
        run: ./vendor/bin/pint

      - name: set up database
        working-directory: ./server
        run: cp .env.example .env

      - name: Update .env for MySQL
        working-directory: ./server
        run: |
          echo "DB_CONNECTION=mysql" >> .env 
          echo "DB_HOST=127.0.0.1" >> .env
          echo "DB_PORT=3306" >> .env
          echo "DB_DATABASE=testing" >> .env
          echo "DB_USERNAME=root" >> .env
          echo "DB_PASSWORD=admin" >> .env
          echo "DB_CONNECTION=mysql" >> .env.testing
          echo "DB_HOST=127.0.0.1" >> .env.testing
          echo "DB_PORT=3306" >> .env.testing
          echo "DB_DATABASE=testing" >> .env.testing
          echo "DB_USERNAME=root" >> .env.testing
          echo "DB_PASSWORD=admin" >> .env.testing

      - name: Migrate database
        working-directory: ./server
        run: php artisan migrate:fresh --seed

      - name: Test back-end
        working-directory: ./server
        run: php artisan test --coverage --min=80
