name: CI

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

jobs:
  backend:
    name: backend (pytest + alembic)
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_USER: mealplanner
          POSTGRES_PASSWORD: password
          POSTGRES_DB: mealplanner_test
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 5s
          --health-timeout 5s
          --health-retries 10
    env:
      TEST_DATABASE_URL: postgresql://mealplanner:password@localhost:5432/mealplanner_test
      DATABASE_URL: postgresql://mealplanner:password@localhost:5432/mealplanner_test
      SECRET_KEY: ci-secret-key-not-for-prod
      ADMIN_TOKEN: ci-admin-token
      SESSION_PASSWORD: test-family-password
      EMAIL_BACKEND: console
    defaults:
      run:
        working-directory: backend
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python 3.11
        uses: actions/setup-python@v5
        with:
          python-version: "3.11"
          cache: pip
          cache-dependency-path: |
            backend/requirements.txt
            backend/requirements-dev.txt

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
          pip install -r requirements-dev.txt

      - name: Wait for Postgres
        run: |
          for i in $(seq 1 30); do
            pg_isready -h localhost -p 5432 -U mealplanner && exit 0
            sleep 1
          done
          echo "Postgres never became ready" >&2
          exit 1

      - name: Alembic upgrade head
        run: alembic upgrade head

      - name: Run pytest
        run: pytest -q

  frontend:
    name: frontend (build)
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: frontend
    steps:
      - uses: actions/checkout@v4

      - name: Set up Node 20
        uses: actions/setup-node@v4
        with:
          node-version: "20"
          cache: npm
          cache-dependency-path: frontend/package-lock.json

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build
