const express = require('express');
const router = express.Router();
const svgCaptcha = require('svg-captcha');

const captchaStore = {};
const CAPTCHA_EXPIRE = 5 * 60 * 1000;

/**
 * 校验短信验证码（服务端）. 供登录/注册侧调用，防止仅凭任意验证码绕过登录。
 * 校验通过后一次性消费（删除），同一验证码不可重复使用。
 * @param {string} phone 手机号
 * @param {string} code 用户提交的验证码
 * @returns {boolean}
 */
function verifySms(phone, code) {
  if (!phone || !code) return false;
  for (const key of Object.keys(captchaStore)) {
    const record = captchaStore[key];
    if (record.phone === phone && String(record.text) === String(code) && record.expires > Date.now()) {
      delete captchaStore[key];
      return true;
    }
  }
  return false;
}

router.get('/image', (req, res) => {
  const captcha = svgCaptcha.create({
    size: 4, fontSize: 50, width: 120, height: 40,
    noise: 2, color: true, background: '#f0f4ff',
  });
  const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
  captchaStore[id] = {
    text: captcha.text.toLowerCase(),
    expires: Date.now() + CAPTCHA_EXPIRE
  };
  for (const key in captchaStore) {
    if (captchaStore[key].expires < Date.now()) delete captchaStore[key];
  }
  res.cookie('captcha_id', id, { maxAge: 5 * 60 * 1000, httpOnly: true, sameSite: 'lax' });
  res.set('x-captcha-text', captcha.text.toLowerCase());
  res.json({
    code: 0,
    data: { id, svg: captcha.data }
  });
});

router.post('/verify', (req, res) => {
  const { id, text } = req.body;
  if (!id || !text) return res.json({ code: 1, message: '参数不完整' });
  const record = captchaStore[id];
  if (!record) return res.json({ code: 1, message: '验证码已过期' });
  if (record.expires < Date.now()) {
    delete captchaStore[id];
    return res.json({ code: 1, message: '验证码已过期' });
  }
  if (record.text !== text.toLowerCase()) {
    return res.json({ code: 1, message: '验证码错误' });
  }
  delete captchaStore[id];
  res.json({ code: 0, message: '验证通过' });
});

router.post('/sms', (req, res) => {
  const { phone } = req.body;
  if (!phone) return res.json({ code: 1, message: '请输入手机号' });
  const code = String(Math.floor(100000 + Math.random() * 900000));
  const id = 'sms_' + Date.now().toString(36);
  captchaStore[id] = { text: code, expires: Date.now() + CAPTCHA_EXPIRE, phone };
  console.log('[短信验证码]', phone, '->', code);
  res.json({
    code: 0, data: { id },
    message: '验证码已发送' + (process.env.NODE_ENV !== 'production' ? ': ' + code : '')
  });
});

module.exports = router;
module.exports.verifySms = verifySms;
