import express, { Application, Request, Response, NextFunction } from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import router from './routes/index';
import { config } from './config/index';
import { initializeDatabase } from './database';

const app: Application = express();

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 数据库初始化中间件
app.use(async (req: Request, res: Response, next: NextFunction) => {
  try {
    await initializeDatabase();
    next();
  } catch (error) {
    console.error('❌ 数据库初始化失败:', error);
    res.status(500).json({ error: '数据库初始化失败' });
  }
});

// 路由
app.use('/api', router);

// 健康检查端点
app.get('/health', (req: Request, res: Response) => {
  res.status(200).json({ 
    status: 'UP', 
    timestamp: new Date().toISOString() 
  });
});

// 404 处理
app.use((req: Request, res: Response) => {
  res.status(404).json({ 
    error: '端点未找到' 
  });
});



export default app;