const { Router } = require("express");
const jwt = require("jsonwebtoken");
const config = require("../config");
const { code2session } = require("../services/wechat");

const router = Router();

router.get("/login", async (req, res) => {
  try {
    const { code } = req.query;
    if (!code) {
      return res.status(400).json({ error: "缺少 code 参数" });
    }

    const { openid } = await code2session(code);

    const token = jwt.sign({ openid }, config.jwtSecret, {
      expiresIn: config.jwtExpiresIn,
    });

    res.json({ access_token: token });
  } catch (err) {
    console.error("登录失败:", err.message);
    res.status(500).json({ error: "登录失败，请稍后重试" });
  }
});

module.exports = router;
