name: CI

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main, develop ]

jobs:
  test:
    runs-on: ubuntu-latest
    
    services:
      {% if config.use_postgresql %}
      postgres:
        image: postgres:{{ config.postgresql_version }}
        env:
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: {{ project_name }}_test
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432
      {% endif %}
      
      {% if config.use_celery %}
      redis:
        image: redis:7-alpine
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 6379:6379
      {% endif %}

    steps:
    - uses: actions/checkout@v4
    
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.11'
    
    {% if config.frontend_pipeline != 'none' %}
    - name: Set up Node.js
      uses: actions/setup-node@v4
      with:
        node-version: '18'
        cache: 'npm'
    
    - name: Install frontend dependencies
      run: npm ci
    
    - name: Build frontend assets
      run: npm run build
    {% endif %}
    
    - name: Install Python dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements/development.txt
    
    - name: Run linting
      run: |
        flake8 .
        black --check .
        isort --check-only .
    
    - name: Run tests
      env:
        DJANGO_SETTINGS_MODULE: {{ project_name }}.settings.development
        {% if config.use_postgresql %}
        DB_HOST: localhost
        DB_PORT: 5432
        DB_NAME: {{ project_name }}_test
        DB_USER: postgres
        DB_PASSWORD: postgres
        {% endif %}
        {% if config.use_celery %}
        CELERY_BROKER_URL: redis://localhost:6379/0
        CELERY_RESULT_BACKEND: redis://localhost:6379/0
        {% endif %}
        SECRET_KEY: test-secret-key-for-ci
      run: |
        python manage.py migrate
        pytest --cov=. --cov-report=xml
    
    - name: Upload coverage to Codecov
      uses: codecov/codecov-action@v3
      with:
        file: ./coverage.xml
        flags: unittests
        name: codecov-umbrella
        fail_ci_if_error: false

  {% if config.use_docker %}
  docker:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Build Docker image
      run: docker build -t {{ project_name }}:latest .
    
    - name: Test Docker image
      run: |
        docker run --rm {{ project_name }}:latest python manage.py check
  {% endif %}