name: Frontend Workflow

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - "*"

jobs:
  install-front:
    uses: ./.github/workflows/front-dependencies-installation.yml
    with:
      node_version: "22.x"

  lint-front:
    runs-on: ubuntu-latest
    needs: install-front
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "22.x"
      - name: Restore the frontend cache
        uses: actions/cache@v4
        with:
          path: "src/frontend/**/node_modules"
          key: front-node_modules-${{ hashFiles('src/frontend/**/yarn.lock') }}
          fail-on-cache-miss: true

      - name: Check linting
        run: cd src/frontend/ && yarn lint

  test-unit:
    runs-on: ubuntu-latest
    needs: install-front
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "22.x"

      - name: Restore the frontend cache
        uses: actions/cache@v4
        with:
          path: "src/frontend/**/node_modules"
          key: front-node_modules-${{ hashFiles('src/frontend/**/yarn.lock') }}
          fail-on-cache-miss: true

      - name: Run unit tests
        run: |
          cd src/frontend/apps/calendars
          yarn test

  test-e2e:
    runs-on: ubuntu-latest
    needs: install-front
    strategy:
      matrix:
        browser:
          - chromium
          - webkit
          - firefox
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "22.x"

      - name: Restore the frontend cache
        uses: actions/cache@v4
        with:
          path: "src/frontend/**/node_modules"
          key: front-node_modules-${{ hashFiles('src/frontend/**/yarn.lock') }}
          fail-on-cache-miss: true

      - name: Install Playwright Browsers
        run: |
          cd src/frontend/apps/e2e
          npx playwright install --with-deps ${{matrix.browser}}

      - name: Start Docker services
        run: |
          make bootstrap-e2e

      - name: Start frontend
        run: |
          cd src/frontend && yarn dev &

      - name: Wait for Keycloak to be ready
        run: |
          timeout 30 bash -c 'while [[ "$(curl -s -o /dev/null -w ''%{http_code}'' http://localhost:8083/)" != "302" ]]; do echo "Waiting for Keycloak..." && sleep 2; done' && echo "Keycloak is ready!"

      - name: Run e2e tests
        run: |
          cd src/frontend/apps/e2e
          yarn test --project=${{ matrix.browser }}

      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: report-${{ matrix.browser }}
          path: src/frontend/apps/e2e/report/
          retention-days: 7
