require('dotenv').config();
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const morgan = require('morgan');
const path = require('path');
const fs = require('fs');

// 创建Express应用
const app = express();

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

// 日志配置
const accessLogStream = fs.createWriteStream(
  path.join(__dirname, 'logs', 'access.log'), 
  { flags: 'a' }
);
app.use(morgan('combined', { stream: accessLogStream }));

// 数据库连接
const sequelize = require('./config/database');

// 测试数据库连接
sequelize.authenticate()
  .then(() => {
    console.log('数据库连接成功');
  })
  .catch(err => {
    console.error('数据库连接失败:', err);
  });

// ==================== 重新设计的路由结构 ====================
// 按照银行端的模式，统一使用 /api/ 前缀，按功能模块分组

// 1. 认证相关
app.use('/api/auth', require('./routes/auth'));

// 2. 仪表盘和统计
app.use('/api/dashboard', require('./routes/dashboard'));

// 3. 政府管理核心功能
app.use('/api/government', require('./routes/government'));

// 4. 人员管理
app.use('/api/personnel', require('./routes/personnel'));

// 5. 监管相关
app.use('/api/supervision', require('./routes/supervision'));

// 6. 审批流程
app.use('/api/approval', require('./routes/approval'));
app.use('/api/approval-process', require('./routes/approvalProcess'));

// 7. 疫情管理
app.use('/api/epidemic', require('./routes/epidemic'));
app.use('/api/epidemic-record', require('./routes/epidemicRecord'));
app.use('/api/epidemic-activity', require('./routes/epidemicActivity'));
app.use('/api/vaccine', require('./routes/vaccine'));

// 8. 屠宰管理
app.use('/api/slaughter', require('./routes/slaughter'));
app.use('/api/harmless', require('./routes/harmless'));
app.use('/api/harmless-place', require('./routes/harmlessPlace'));

// 9. 智能硬件管理
app.use('/api/smart-earmark', require('./routes/smartEarmark'));
app.use('/api/smart-host', require('./routes/smartHost'));

// 10. 服务管理
app.use('/api/service', require('./routes/service'));

// 11. 可视化数据
app.use('/api/visualization', require('./routes/visualization'));

// 12. 系统管理
app.use('/api/system', require('./routes/system'));

// 13. 文件管理
app.use('/api/files', require('./routes/files'));

// 14. 其他功能
app.use('/api/production-material-certification', require('./routes/productionMaterialCertification'));
app.use('/api/cattle-academy', require('./routes/cattleAcademy'));
app.use('/api/device-warning', require('./routes/deviceWarning'));

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date() });
});

// 根路径
app.get('/', (req, res) => {
  res.json({
    success: true,
    message: '政府管理系统API服务',
    version: '1.0.0',
    health: '/health'
  });
});

// 错误处理
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ 
    code: 500, 
    message: 'Internal Server Error',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 启动服务器
const PORT = process.env.PORT || 5352;
const HOST = process.env.HOST || '0.0.0.0';
app.listen(PORT, HOST, () => {
  console.log(`政府管理系统后端服务已启动，地址: ${HOST}:${PORT}`);
});

module.exports = app;
