const jwt = require("jsonwebtoken");
const config = require("./config");
const store = require("./store");
const { streamDreamInterpretation } = require("./services/deepseek");

function handleConnection(ws, req) {
  // 从 url 参数或 header 中提取 token
  const url = new URL(req.url, "http://localhost");
  const token = url.searchParams.get("token") || req.headers["authorization"];

  let userId = null;
  try {
    const payload = jwt.verify(token, config.jwtSecret);
    userId = payload.openid;
  } catch {
    ws.send(
      JSON.stringify({ act: "error", message: "请先登录后再解梦" })
    );
    ws.close(4001, "未授权");
    return;
  }

  let fullInterpretation = "";

  ws.on("message", async (raw) => {
    let msg;
    try {
      msg = JSON.parse(raw.toString());
    } catch {
      ws.send(JSON.stringify({ act: "error", message: "消息格式错误" }));
      return;
    }

    if (msg.act !== "start_generate") return;

    const { message: dream, template_name } = msg.payload || {};
    if (!dream || !dream.trim()) {
      ws.send(JSON.stringify({ act: "error", message: "请填写梦境内容" }));
      return;
    }

    if (template_name !== "jiemeng") {
      ws.send(JSON.stringify({ act: "error", message: "不支持的模板" }));
      return;
    }

    fullInterpretation = "";

    try {
      for await (const chunk of streamDreamInterpretation(dream.trim())) {
        fullInterpretation += chunk;
        ws.send(JSON.stringify({ act: "answer", message: chunk }));
      }

      const recordId = store.saveRecord(
        userId,
        dream.trim(),
        fullInterpretation
      );

      ws.send(
        JSON.stringify({
          act: "answer_finish",
          payload: { record_id: recordId },
        })
      );
    } catch (err) {
      console.error("DeepSeek 调用失败:", err.message);
      ws.send(
        JSON.stringify({
          act: "error",
          message: "AI 解析服务暂时不可用，请稍后重试",
        })
      );
    }
  });

  ws.on("close", () => {
    // 清理工作（如有需要）
  });
}

module.exports = { handleConnection };
