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);
  });

// 路由
app.use('/api/auth', require('./routes/auth'));
app.use('/api/supervision', require('./routes/supervision'));
app.use('/api/approval', require('./routes/approval'));
app.use('/api/personnel', require('./routes/personnel'));
// 暂时注释掉warehouse路由，因为在智能项圈页面不使用，且有500错误
// app.use('/api/warehouse', require('./routes/warehouse'));
app.use('/api/epidemic', require('./routes/epidemic'));
app.use('/api/service', require('./routes/service'));
app.use('/api/visualization', require('./routes/visualization'));
app.use('/api/system', require('./routes/system'));
app.use('/api/files', require('./routes/files'));
app.use('/api/government', require('./routes/government'));
app.use('/api/dashboard', require('./routes/dashboard'));
app.use('/api/smart-earmark', require('./routes/smartEarmark'));
app.use('/api/smart-host', require('./routes/smartHost'));
app.use('/api/slaughter', require('./routes/slaughter'));
app.use('/api/harmless', require('./routes/harmless'));
app.use('/api/harmless-place', require('./routes/harmlessPlace'));
app.use('/api/epidemic-record', require('./routes/epidemicRecord'));
app.use('/api/vaccine', require('./routes/vaccine'));
app.use('/api/epidemic-activity', require('./routes/epidemicActivity'));
app.use('/api/production-material-certification', require('./routes/productionMaterialCertification'));
app.use('/api/approval-process', require('./routes/approvalProcess'));
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.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}`);
});