# Single compose file for all environments.
# Switch environments by copying the right .env file:
#   cp .env.dev .env      → dev server
#   cp .env.local .env    → local machine
#   cp .env.staging .env  → staging
#
# Commands are identical everywhere:
#   docker compose up -d --build
#   docker compose exec api alembic upgrade head
#   docker compose logs -f api
#   docker compose down

x-app-common: &app-common
  build:
    context: .
    dockerfile: Dockerfile
    target: production
  env_file:
    - .env
  environment:
    DATABASE_URL: "postgresql+psycopg://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}"
  volumes:
    - .:/app
  networks:
    - indelis_net
  restart: unless-stopped
  depends_on:
    postgres:
      condition: service_healthy
    redis:
      condition: service_healthy

services:

  # ── FastAPI Application ───────────────────────────────────────────────────
  api:
    <<: *app-common
    container_name: ${COMPOSE_PROJECT_NAME}_api
    ports:
      - "${APP_PORT:-8000}:8000"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health/live"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 20s

  # ── ARQ Background Worker ─────────────────────────────────────────────────
  worker:
    <<: *app-common
    container_name: ${COMPOSE_PROJECT_NAME}_worker
    command: arq src.worker.arq_app.WorkerSettings
    depends_on:
      api:
        condition: service_healthy

  # ── PostgreSQL 15 + PostGIS ───────────────────────────────────────────────
  postgres:
    image: postgis/postgis:15-3.4-alpine
    container_name: ${COMPOSE_PROJECT_NAME}_postgres
    environment:
      POSTGRES_DB: ${POSTGRES_DB}
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_INITDB_ARGS: "--encoding=UTF8 --locale=C"
    ports:
      - "${POSTGRES_PORT:-5432}:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - indelis_net
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 15s
    restart: unless-stopped

  # ── Redis 7 ──────────────────────────────────────────────────────────────
  redis:
    image: redis:7-alpine
    container_name: ${COMPOSE_PROJECT_NAME}_redis
    ports:
      - "${REDIS_PORT:-6379}:6379"
    volumes:
      - redis_data:/data
    networks:
      - indelis_net
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
    command: >
      redis-server
      --appendonly yes
      --maxmemory ${REDIS_MAXMEMORY:-256mb}
      --maxmemory-policy allkeys-lru
    restart: unless-stopped

volumes:
  postgres_data:
    driver: local
  redis_data:
    driver: local

networks:
  indelis_net:
    driver: bridge
