name: Django CI

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

jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest]
        python-version: ["3.13"]

    services:
      postgres:
        image: postgis/postgis:16-3.4
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: test_thrillwiki
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        # Services only run on Linux runners
        if: runner.os == 'Linux'

    steps:
    - uses: actions/checkout@v6

    - name: Install Homebrew on Linux
      if: runner.os == 'Linux'
      run: |
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
        echo "/home/linuxbrew/.linuxbrew/bin" >> $GITHUB_PATH

    - name: Install GDAL with Homebrew
      run: brew install gdal

    - name: Install PostGIS on macOS
      if: runner.os == 'macOS'
      run: |
        brew install postgresql@16 postgis
        brew services start postgresql@16
        sleep 5
        /opt/homebrew/opt/postgresql@16/bin/createuser -s postgres || true
        /opt/homebrew/opt/postgresql@16/bin/createdb -U postgres test_thrillwiki || true
        /opt/homebrew/opt/postgresql@16/bin/psql -U postgres -d test_thrillwiki -c "CREATE EXTENSION IF NOT EXISTS postgis;" || true

    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v6
      with:
        python-version: ${{ matrix.python-version }}

    - name: Install UV
      run: |
        curl -LsSf https://astral.sh/uv/install.sh | sh
        echo "$HOME/.cargo/bin" >> $GITHUB_PATH

    - name: Cache UV dependencies
      uses: actions/cache@v5
      with:
        path: ~/.cache/uv
        key: ${{ runner.os }}-uv-${{ hashFiles('backend/pyproject.toml') }}
        restore-keys: |
          ${{ runner.os }}-uv-

    - name: Install Dependencies
      working-directory: backend
      run: |
        uv sync --frozen

    - name: Security Audit
      working-directory: backend
      run: |
        uv pip install pip-audit
        uv run pip-audit || true
      continue-on-error: true

    - name: Run Tests
      working-directory: backend
      env:
        DJANGO_SETTINGS_MODULE: config.django.test
        TEST_DB_NAME: test_thrillwiki
        TEST_DB_USER: postgres
        TEST_DB_PASSWORD: postgres
        TEST_DB_HOST: localhost
        TEST_DB_PORT: 5432
      run: |
        uv run python manage.py test --settings=config.django.test --parallel
