name: "Back"
on:
  pull_request:
    branches: [ main ]

jobs:

  changes:
    runs-on: ubuntu-latest
    # Required permissions
    permissions:
      pull-requests: read
    # Set job outputs to values from filter step
    outputs:
      backend: ${{ steps.filter.outputs.backend }}
      frontend: ${{ steps.filter.outputs.frontend }}
      scoro: ${{ steps.filter.outputs.scoro }}
    steps:
    # For pull requests it's not necessary to checkout the code
    - uses: dorny/paths-filter@v2
      id: filter
      with:
        filters: |
          backend:
            - 'backend/**'
          frontend:
            - 'frontend/**'
          scoro:
            - 'scorometer/**'
  back_build:
    runs-on: ubuntu-latest
    timeout-minutes: 10

    needs: changes
    if: ${{ needs.changes.outputs.backend == 'true' }}
    defaults:
      run:
        working-directory: ./back
    steps:
      - uses: actions/checkout@v3

      - name: Build Docker
        run: docker build -t testback .


  back_test:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    needs: [ back_build ]
    if: ${{ needs.changes.outputs.frontend == 'true' }}

    steps:
      - uses: actions/checkout@v3
        with:
          submodules: recursive
          fetch-depth: 0

      - name: Copy env file to github secret env file
        run: cp .env.example .env

      - name: Build and start the service
        run: docker-compose up -d meilisearch back db 

      - name: Perform healthchecks
        run: |
          docker-compose ps -a
          docker-compose logs
          wget --retry-connrefused http://localhost:3000 || (docker-compose logs && exit 1)

      - name: Run robot tests
        run: |
          export API_KEY_ROBOT=ROBOTO
          pip install -r back/test/robot/requirements.txt
          robot -d out back/test/robot/
      - uses: actions/upload-artifact@v3
        if: always()
        with:
          name: results
          path: out

      - name: Write results to Pull Request and Summary
        if: always() && github.event_name == 'pull_request'
        uses: joonvena/robotframework-reporter-action@v2.1
        with:
          report_path: out/
          gh_access_token: ${{ secrets.GITHUB_TOKEN }}
          only_summary: false

      - name: Write results to Summary
        if: always() && github.event_name != 'pull_request'
        uses: joonvena/robotframework-reporter-action@v2.1
        with:
          report_path: out/
          gh_access_token: ${{ secrets.GITHUB_TOKEN }}
          only_summary: true

      - name: stop the service
        run: docker-compose down
