name: CI/CD Pipeline

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  frontend-test:
    runs-on: ubuntu-latest
    container: node:20
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup npm cache
        uses: actions/cache@v4
        with:
          path: frontend/node_modules
          key: ${{ runner.os }}-npm-${{ hashFiles('frontend/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-npm-

      - name: Install dependencies
        working-directory: frontend
        run: npm ci

      - name: Run unit tests
        working-directory: frontend
        run: npm test

      - name: Build production
        working-directory: frontend
        run: npm run build

  backend-test:
    runs-on: ubuntu-latest
    container: python:3.12-slim
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install system dependencies
        run: |
          apt-get update && apt-get install -y --no-install-recommends gcc libpq-dev && rm -rf /var/lib/apt/lists/*

      - name: Setup pip cache
        uses: actions/cache@v4
        with:
          path: ~/.cache/pip
          key: ${{ runner.os }}-pip-${{ hashFiles('backend/requirements.txt') }}
          restore-keys: |
            ${{ runner.os }}-pip-

      - name: Install Python dependencies
        working-directory: backend
        run: pip install --no-cache-dir -r requirements.txt

      - name: Run tests
        working-directory: backend
        run: pytest -v

  docker-build:
    runs-on: ubuntu-latest
    needs: [frontend-test, backend-test]
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Build frontend Docker image
        run: docker build -t hms-frontend:ci ./frontend

      - name: Build backend Docker image
        run: docker build -t hms-backend:ci ./backend

      - name: Validate docker-compose
        run: docker compose config --quiet
