const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const router = require('./routes/index');
const { initializeDatabase } = require('./database');
const config = require('./config');

const app = express();

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

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

// 在数据库初始化后添加
app.use('/api', router);

// 打印所有注册的端点
app._router.stack.forEach(middleware => {
  if (middleware.route) {
    // 应用程序级别的路由
    console.log(`${Object.keys(middleware.route.methods).join(', ')} ${middleware.route.path}`);
  } else if (middleware.name === 'router') {
    // 路由级别的中间件
    middleware.handle.stack.forEach(handler => {
      if (handler.route) {
        console.log(`${Object.keys(handler.route.methods).join(', ')} ${handler.route.path}`);
      }
    });
  }
});

module.exports = app;