const express = require('express')
const http = require('http')
const cors = require('cors')
const ChatServer = require('./chat')

class AppServer {
    constructor() {
        this.app = express()
        
        // 配置CORS
        this.app.use(cors({
            origin: process.env.ALLOWED_ORIGINS ? 
                process.env.ALLOWED_ORIGINS.split(',') : 
                'http://localhost:5173', // Vite默认开发端口
            methods: ['GET', 'POST']
        }))

        // 创建HTTP服务器
        this.server = http.createServer(this.app)
        
        // 初始化WebSocket服务器
        this.chatServer = new ChatServer(this.server)

        // 添加健康检查接口
        this.app.get('/health', (req, res) => {
            res.json({ status: 'ok', timestamp: new Date().toISOString() })
        })
    }

    start(port) {
        this.server.listen(port, () => {
            console.log(`聊天服务器已启动，监听端口 ${port}`)
            console.log(`健康检查接口: http://localhost:${port}/health`)
        })
    }
}

module.exports = AppServer