name: Build and Test

on:
  pull_request:
    branches:
      - master
  push:
    branches:
      - master

jobs:
  build-and-test:
    runs-on: ubuntu-latest

    env:
      POSTGRES_USERNAME: planka
      POSTGRES_PASSWORD: planka
      POSTGRES_DATABASE: planka

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

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'

      - name: Set up PostgreSQL
        uses: ikalnytskyi/action-setup-postgres@v5
        with:
          username: ${{ env.POSTGRES_USERNAME }}
          password: ${{ env.POSTGRES_PASSWORD }}
          database: ${{ env.POSTGRES_DATABASE }}

      - name: Cache Node.js modules
        uses: actions/cache@v3
        with:
          path: client/node_modules
          key: ${{ runner.os }}-node-${{ hashFiles('client/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      - name: Install dependencies and build client
        run: |
          npm install
          cd client
          npm run build

      - name: Set up and start server for testing
        env:
          DEFAULT_ADMIN_EMAIL: demo@demo.demo
          DEFAULT_ADMIN_PASSWORD: demo
          DEFAULT_ADMIN_NAME: Demo Demo
          DEFAULT_ADMIN_USERNAME: demo
        run: |
          client/tests/setup-symlinks.sh
          cd server
          cp .env.sample .env
          sed -i "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://${POSTGRES_USERNAME}:${POSTGRES_PASSWORD}@localhost/${POSTGRES_DATABASE}|" .env
          npm run db:init
          npm start --prod &

      - name: Wait for server to start
        run: |
          sudo apt-get install wait-for-it -y
          wait-for-it -h localhost -p 1337 -t 10

      - name: Seed database with terms signature
        run: |
          TERMS_SIGNATURE=$(sha256sum terms/en-US/extended.md | awk '{print $1}')
          PGPASSWORD=$POSTGRES_PASSWORD psql -h localhost -U $POSTGRES_USERNAME -d $POSTGRES_DATABASE -c "UPDATE user_account SET terms_signature = '$TERMS_SIGNATURE';"
        working-directory: ./server

      - name: Run UI tests
        run: |
          npx playwright install chromium
          npm run test:acceptance
        working-directory: ./client
