import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import { config } from './config';
import marketRoutes from './api/market';
import analysisRoutes from './api/analysis';
import riskRoutes from './api/risk';
import configRoutes from './api/config';
import watchlistRoutes from './api/watchlist';
import pushRoutes from './api/push';
import { logger } from './utils/logger';

const app = express();

// 中间件配置
app.use(helmet());
app.use(cors(config.cors));
app.use(morgan('combined'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 速率限制
app.use(rateLimit({
  windowMs: config.rateLimit.windowMs,
  max: config.rateLimit.max,
  message: {
    success: false,
    message: '请求过于频繁，请稍后再试'
  }
}));

// 健康检查
app.get('/health', (req, res) => {
  res.status(200).json({ success: true, message: '服务运行正常' });
});

// API路由注册
app.use('/api/market', marketRoutes);
app.use('/api/analysis', analysisRoutes);
app.use('/api/risk', riskRoutes);
app.use('/api/config', configRoutes);
app.use('/api/watchlist', watchlistRoutes);
app.use('/api/push', pushRoutes);

// 404处理
app.use((req, res) => {
  res.status(404).json({ success: false, message: '接口不存在' });
});

// 错误处理
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
  logger.error(err.stack);
  res.status(500).json({ success: false, message: '服务器内部错误' });
});

// 启动服务器
const port = config.port || 3007;

// 启动服务器
async function startServer() {
  try {
    // 启动Express服务器
    const server = app.listen(port, () => {
      logger.log(`服务器运行在 http://localhost:${port}`);
    });

    // 处理服务器关闭事件
    function handleShutdown() {
      logger.log('正在关闭服务器...');
      // 关闭Express服务器
      server.close(() => {
        logger.log('服务器已关闭');
        process.exit(0);
      });
    }

    // 监听终止信号
    process.on('SIGINT', handleShutdown);
    process.on('SIGTERM', handleShutdown);
    process.on('exit', handleShutdown);
  } catch (error) {
    logger.error('启动服务器时出错:', error);
  }
}

// 启动服务器
startServer();

export default app;