services:
  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-omnitrack}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-omnitrack}
      POSTGRES_DB: ${POSTGRES_DB:-omnitrack}
    # Host port 5433 avoids conflict with a local PostgreSQL on 5432 (Windows/Docker Desktop).
    # Inside the compose network the service is still `db:5432` — DATABASE_URL unchanged for containers.
    ports:
      - "127.0.0.1:5433:5432"
    volumes:
      - omnitrack_pg:/var/lib/postgresql/data
    healthcheck:
      test:
        [
          "CMD-SHELL",
          "pg_isready -U ${POSTGRES_USER:-omnitrack} -d ${POSTGRES_DB:-omnitrack}",
        ]
      interval: 5s
      timeout: 5s
      retries: 10

  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      DATABASE_URL: ${DATABASE_URL:-postgresql://omnitrack:omnitrack@db:5432/omnitrack}
      SESSION_SECRET: ${SESSION_SECRET:-change-this-secret-in-production}
      NODE_ENV: production
      # Move active buses on the map for demos (disable when all positions must come from trackers).
      ENABLE_BUS_SIMULATION: ${ENABLE_BUS_SIMULATION:-true}
      # When the DB already has users but almost no students, load Iraq demo (28 schools, 28 buses, 500 students + parents).
      # Disable on production stacks with real (partial) data.
      SEED_IRAQ_BULK: ${SEED_IRAQ_BULK:-true}
      # Do not set TRUST_PROXY unless the app sits behind a reverse proxy with X-Forwarded-Proto (would break cookies on http://localhost).
      # Optional (Iraq / blocked Teltonika cloud FOTA): mount firmware binaries + public URL for operator export
      # FIRMWARE_FILES_PATH: /data/firmware
      # FIRMWARE_PUBLIC_BASE_URL: https://your-domain.example/fleet-firmware
    depends_on:
      db:
        condition: service_healthy

  telematics-gateway:
    build: .
    command: ["node", "dist/telematics-gateway.cjs"]
    environment:
      # Allow Teltonika devices to connect before staff adds IMEI in UI (stub row is created).
      TELEM_GATEWAY_ALLOW_UNKNOWN_IMEI: "true"
      DATABASE_URL: ${DATABASE_URL:-postgresql://omnitrack:omnitrack@db:5432/omnitrack}
      TELEM_GATEWAY_BIND: "0.0.0.0"
      TELEM_GATEWAY_PORT: "5027"
      METRICS_PORT: "9092"
      NODE_ENV: production
    ports:
      - "5027:5027"
      - "127.0.0.1:9092:9092"
    # Image HEALTHCHECK hits :3000 (app only). Gateway exposes metrics on 9092, not HTTP on 3000.
    healthcheck:
      test:
        [
          "CMD-SHELL",
          "node -e \"fetch('http://127.0.0.1:9092/metrics').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))\"",
        ]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 45s
    depends_on:
      db:
        condition: service_healthy
      app:
        condition: service_started

volumes:
  omnitrack_pg:
