const http = require("http");
const express = require("express");
const cors = require("cors");
const { WebSocketServer } = require("ws");
const config = require("./config");
const authRoutes = require("./routes/auth");
const posterRoutes = require("./routes/poster");
const { handleConnection } = require("./wsHandler");

const app = express();

app.use(cors());
app.use(express.json());

// HTTP 路由
app.use(authRoutes);
app.use(posterRoutes);

// 健康检查
app.get("/", (req, res) => {
  res.json({ status: "ok", service: "周公解梦 API" });
});

const server = http.createServer(app);

// WebSocket 服务器
const wss = new WebSocketServer({ server, path: "/chat" });

wss.on("connection", (ws, req) => {
  handleConnection(ws, req);
});

server.listen(config.port, () => {
  console.log(`服务已启动: http://localhost:${config.port}`);
  console.log(`WebSocket: ws://localhost:${config.port}/chat`);
  console.log("接口列表:");
  console.log("  GET  /login?code=xxx           — 微信登录");
  console.log("  GET  /generate-post?record_id=  — 生成分享海报");
  console.log("  WSS  /chat                     — 解梦对话");
});
