version: '3.8'

services:
  # 前端服务
  frontend:
    build:
      context: ./app
      dockerfile: Dockerfile
    ports:
      - "80:80"
    depends_on:
      - backend
    networks:
      - futures-network
    restart: unless-stopped

  # 后端服务
  backend:
    build:
      context: ./app/server
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - PORT=3000
      - DATABASE_URL=postgresql://futures_user:futures_pass@postgres:5432/futures_analysis?schema=public
      - REDIS_URL=redis://redis:6379
      - JWT_SECRET=${JWT_SECRET:-your-super-secret-jwt-key-change-this-in-production}
      - JWT_EXPIRES_IN=1h
      - JWT_REFRESH_EXPIRES_IN=7d
      - MARKET_DATA_PROVIDER=mock
      - CORS_ORIGIN=http://localhost
    depends_on:
      - postgres
      - redis
      - migrate
    networks:
      - futures-network
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "node", "-e", "require('http').get('http://localhost:3000/api/v1/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"]
      interval: 30s
      timeout: 3s
      retries: 3

  # 数据库迁移服务
  migrate:
    build:
      context: ./app/server
      dockerfile: Dockerfile
    command: npx prisma migrate deploy
    environment:
      - DATABASE_URL=postgresql://futures_user:futures_pass@postgres:5432/futures_analysis?schema=public
    depends_on:
      postgres:
        condition: service_healthy
    networks:
      - futures-network
    restart: "no"

  # PostgreSQL数据库
  postgres:
    image: postgres:15-alpine
    environment:
      - POSTGRES_USER=futures_user
      - POSTGRES_PASSWORD=futures_pass
      - POSTGRES_DB=futures_analysis
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    networks:
      - futures-network
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U futures_user -d futures_analysis"]
      interval: 5s
      timeout: 5s
      retries: 5

  # Redis缓存
  redis:
    image: redis:7-alpine
    command: redis-server --appendonly yes
    volumes:
      - redis_data:/data
    ports:
      - "6380:6379"
    networks:
      - futures-network
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

  # Nginx反向代理 (可选)
  nginx:
    image: nginx:alpine
    ports:
      - "8080:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
    depends_on:
      - frontend
      - backend
    networks:
      - futures-network
    restart: unless-stopped

volumes:
  postgres_data:
  redis_data:

networks:
  futures-network:
    driver: bridge
