services:
  db:
    image: postgres:17-alpine
    container_name: aurora_db
    environment:
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=${DB_NAME}
    # Uncomment to access DB from host (for debugging/drizzle-kit studio)
    ports:
      - "127.0.0.1:${DB_PORT}:5432"
    volumes:
      # Host-mounted to preserve existing VPS data
      - ./shared/db/data:/var/lib/postgresql/data
    networks:
      - internal
      - web
    healthcheck:
      test: [ "CMD-SHELL", "pg_isready -U ${DB_USER} -d ${DB_NAME}" ]
      interval: 5s
      timeout: 5s
      retries: 5

  app:
    container_name: aurora_app
    restart: unless-stopped
    build:
      context: .
      dockerfile: Dockerfile
      target: development # Use development stage
    working_dir: /app
    ports:
      - "127.0.0.1:3000:3000"
    volumes:
      # Mount source code for hot reloading
      - .:/app
      # Use named volumes for node_modules (prevents host overwrite + caches deps)
      - app_node_modules:/app/node_modules
    environment:
      - HOST=0.0.0.0
      - DB_USER=${DB_USER}
      - DB_PASSWORD=${DB_PASSWORD}
      - DB_NAME=${DB_NAME}
      - DB_PORT=5432
      - DB_HOST=db
      - DISCORD_BOT_TOKEN=${DISCORD_BOT_TOKEN}
      - DISCORD_GUILD_ID=${DISCORD_GUILD_ID}
      - DISCORD_CLIENT_ID=${DISCORD_CLIENT_ID}
      - DATABASE_URL=postgresql://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
      - DISCORD_CLIENT_SECRET=${DISCORD_CLIENT_SECRET}
      - SESSION_SECRET=${SESSION_SECRET}
      - ADMIN_USER_IDS=${ADMIN_USER_IDS}
      - PANEL_BASE_URL=${PANEL_BASE_URL:-http://localhost:3000}
    depends_on:
      db:
        condition: service_healthy
    networks:
      - internal
      - web
    healthcheck:
      test: [ "CMD", "bun", "-e", "fetch('http://localhost:3000/api/health').then(r => r.ok ? process.exit(0) : process.exit(1)).catch(() => process.exit(1))" ]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s
    command: bun run dev

  studio:
    container_name: aurora_studio
    # Reuse the same built image as app (no duplicate builds!)
    extends:
      service: app
    # Clear inherited ports from app and only expose studio port
    ports: !override
      - "127.0.0.1:4983:4983"
    # Override healthcheck since studio doesn't serve on port 3000
    healthcheck:
      test: [ "CMD", "bun", "-e", "fetch('http://localhost:4983').then(r => process.exit(0)).catch(() => process.exit(1))" ]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 10s
    # Disable restart for studio (it's an on-demand tool)
    restart: "no"
    command: [ "bun", "x", "drizzle-kit", "studio", "--port", "4983", "--host", "0.0.0.0" ]

networks:
  internal:
    driver: bridge
    internal: true # No external access
  web:
    driver: bridge # Can be accessed from host

volumes:
  # Named volumes for node_modules caching
  app_node_modules:
    name: aurora_app_node_modules
