const fs = require('fs');
const path = require('path');
const http = require('http');

// 加载环境变量（支持通过 NODE_ENV 指定配置）
const envFile = process.env.NODE_ENV === 'production' ? '.env.production' : '.env';
require('dotenv').config({ path: envFile });
console.log(`[Server] 加载配置: ${envFile}`);
console.log(`[Server] 数据库: ${process.env.DATABASE_URL?.replace(/:.*@/, ':***@')}`);
const https = require('https');
const express = require('express');
const cors = require('cors');
const { initSocket } = require('./socket');

const app = express();

// 根据环境创建 HTTP 或 HTTPS 服务器
let server;
const SSL_KEY_PATH = process.env.SSL_KEY_PATH;
const SSL_CERT_PATH = process.env.SSL_CERT_PATH;

if (SSL_KEY_PATH && SSL_CERT_PATH && fs.existsSync(SSL_KEY_PATH) && fs.existsSync(SSL_CERT_PATH)) {
  // 生产环境使用 HTTPS/WSS
  const options = {
    key: fs.readFileSync(SSL_KEY_PATH),
    cert: fs.readFileSync(SSL_CERT_PATH),
  };
  server = https.createServer(options, app);
  console.log('[Server] 使用 HTTPS 模式');
} else {
  // 开发环境使用 HTTP/WS
  server = http.createServer(app);
  console.log('[Server] 使用 HTTP 模式');
}

// 中间件
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 路由注册
app.use('/api/rooms', require('./routes/rooms'));
app.use('/api/sessions', require('./routes/sessions'));
app.use('/api/screens', require('./routes/screens'));
app.use('/api/stats', require('./routes/stats'));

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

// 404 兜底
app.use((_req, res) => {
  res.status(404).json({ error: 'Not Found' });
});

// 全局错误处理
app.use((err, _req, res, _next) => {
  console.error('[Error]', err);
  res.status(500).json({ error: err.message || 'Internal Server Error' });
});

// 初始化 Socket.io
initSocket(server);

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`[Server] 运行中，端口: ${PORT}`);
});
