require('dotenv').config({ path: require('path').join(__dirname, '../.env') });

// 设置默认环境变量
if (!process.env.JWT_SECRET) {
  process.env.JWT_SECRET = 'insurance_super_secret_jwt_key_2024_very_long_and_secure';
}

const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('../config/swagger');
const { sequelize, testConnection } = require('../config/database');

const app = express();
const PORT = process.env.PORT || 3000;

// 安全中间件
app.use(helmet());
app.use(cors({
  origin: function (origin, callback) {
    // 允许的域名列表
    const allowedOrigins = [
      process.env.FRONTEND_URL || 'http://localhost:3001',
      'http://127.0.0.1:3001',
      'http://localhost:3002',
      'http://127.0.0.1:3002',
      'https://ad.ningmuyun.com',
      'https://ad.liaoniuyun.com',
      'https://www.ningmuyun.com',
      'https://ningmuyun.com'
    ];
    
    // 允许没有origin的请求（如移动应用、Postman等）
    if (!origin) return callback(null, true);
    
    if (allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      console.log('CORS blocked origin:', origin);
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
  allowedHeaders: [
    'Content-Type', 
    'Authorization', 
    'X-Requested-With',
    'Accept',
    'Cache-Control',
    'Pragma',
    'Origin',
    'Access-Control-Request-Method',
    'Access-Control-Request-Headers'
  ],
  optionsSuccessStatus: 200
}));

// 速率限制 - 开发环境下放宽限制
const limiter = rateLimit({
  windowMs: 1 * 60 * 1000, // 1分钟
  max: 1000, // 限制每个IP每1分钟最多1000个请求
  message: '请求过于频繁，请稍后再试',
  skip: (req) => {
    // 在开发环境下跳过限流
    return process.env.NODE_ENV === 'development';
  }
});
app.use(limiter);

// 解析请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  console.log('请求体:', req.body);
  next();
});

// 静态文件服务
app.use('/uploads', express.static('uploads'));

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

// API路由
app.use('/api/auth', require('../routes/auth'));
app.use('/api/users', require('../routes/users'));
app.use('/api/insurance', require('../routes/insurance'));
app.use('/api/insurance-types', require('../routes/insuranceTypes'));
app.use('/api/policies', require('../routes/policies'));
app.use('/api/claims', require('../routes/claims'));
app.use('/api/system', require('../routes/system'));
app.use('/api/dashboard', require('../routes/dashboard'));
app.use('/api/operation-logs', require('../routes/operationLogs'));
app.use('/api/menus', require('../routes/menus'));
app.use('/api/data-warehouse', require('../routes/dataWarehouse'));
app.use('/api/supervisory-tasks', require('../routes/supervisoryTasks'));
app.use('/api/supervision-tasks', require('../routes/supervisoryTasks'));
app.use('/api/installation-tasks', require('../routes/installationTasks'));
app.use('/api/regulatory-task-completion', require('../routes/regulatoryTaskCompletion'));

// 生资保险相关路由
app.use('/api/livestock-types', require('../routes/livestockTypes'));
app.use('/api/livestock-policies', require('../routes/livestockPolicies'));
app.use('/api/livestock-claims', require('../routes/livestockClaims'));

// 设备管理相关路由
app.use('/api/devices', require('../routes/devices'));
app.use('/api/device-alerts', require('../routes/deviceAlerts'));

// 权限管理相关路由
app.use('/api/permissions', require('../routes/permissions'));
app.use('/api/role-permissions', require('../routes/rolePermissions'));

// API文档路由
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec, {
  explorer: true,
  customCss: '.swagger-ui .topbar { display: none }',
  customSiteTitle: '保险端口系统 API文档'
}));

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    code: 404,
    status: 'error',
    message: '接口不存在',
    timestamp: new Date().toISOString()
  });
});

// 全局错误处理
app.use((err, req, res, next) => {
  console.error('全局错误:', err);
  
  res.status(err.status || 500).json({
    code: err.status || 500,
    status: 'error',
    message: err.message || '服务器内部错误',
    timestamp: new Date().toISOString()
  });
});

// 启动服务器
const startServer = async () => {
  try {
    // 测试数据库连接
    const dbConnected = await testConnection();
    if (!dbConnected) {
      console.warn('⚠️ 数据库连接失败，但服务器仍将继续启动（开发环境）');
    }

    // Redis连接已移除

    app.listen(PORT, () => {
      console.log(`🚀 保险端口后端服务已启动`);
      console.log(`📍 服务地址: http://localhost:${PORT}`);
      console.log(`🌐 环境: ${process.env.NODE_ENV || 'development'}`);
      console.log(`⏰ 启动时间: ${new Date().toLocaleString()}`);
    });
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
};

// 优雅关闭
process.on('SIGINT', async () => {
  console.log('\n🛑 正在关闭服务器...');
  await sequelize.close();
  process.exit(0);
});

// 启动应用
startServer();

module.exports = app;