const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('../../config');
const { get, run } = require('../utils/db');
const { success, fail } = require('../utils/response');
const notification = require('../lib/notification');
// [安全] 登录限流：复用 security.js 的 loginLimiter（15分钟窗口，IP最多10次失败）
const { loginLimiter } = require('../middleware/security');
// ========== 演示账号保护中间件 ==========
function demoSafeGuard(req, res, next) {
  if (req.method !== 'GET') {
    const demoUser = req.admin ? get('SELECT is_demo FROM users WHERE id=?', [req.admin.id]) : null;
    if (demoUser && demoUser.is_demo) {
      return res.status(403).json({ code: 403, message: '演示账号仅限查看，无操作权限' });
    }
  }
  next();
}
// ========== 管理员登录（登录限流防暴力破解） ==========
router.post('/login', loginLimiter, async (req, res) => {
  try {
    const loginName = req.body.username || req.body.phone;
    const password = req.body.password;
    const captchaCode = req.body.captcha;
    const captchaId = req.cookies?.captcha_id || req.body.captcha_id;
    const ip = req.ip || req.headers['x-forwarded-for'] || '';
    const { captchaStore } = require('./admin-captcha');
    if (!captchaId || !captchaStore[captchaId]) {
      return res.json(fail('验证码已过期，请刷新重试'));
    }
    const record = captchaStore[captchaId];
    if (record.expires < Date.now()) {
      delete captchaStore[captchaId];
      return res.json(fail('验证码已过期，请刷新重试'));
    }
    if (record.text !== (captchaCode || '').toLowerCase()) {
      delete captchaStore[captchaId];
      return res.json(fail('验证码错误'));
    }
    delete captchaStore[captchaId];
    const user = get('SELECT * FROM users WHERE phone=?', [loginName]);
    if (!user || !await bcrypt.compare(password, user.password)) {
      run('INSERT INTO login_logs(user_id,phone,ip,user_agent,result,reason) VALUES(?,?,?,?,?,?)',
        [null, loginName, ip, (req.headers['user-agent']||'').slice(0,200), 'fail', '账号或密码错误']);
      return res.json(fail('账号或密码错误'));
    }
    const token = jwt.sign({ userId: user.id }, config.jwtSecret, { expiresIn: config.jwtExpiresIn });
    run('INSERT INTO login_logs(user_id,phone,ip,user_agent,result,reason) VALUES(?,?,?,?,?,?)',
      [user.id, loginName, ip, (req.headers['user-agent']||'').slice(0,200), 'success', '']);
    return res.json(success({ token }, '登录成功'));
  } catch (e) { return res.json(fail('登录失败')); }
});
// ========== 修改密码 ==========
router.put('/password', require('../middleware/auth').authAdmin, demoSafeGuard, async (req, res) => {
  try {
    const { old_password, new_password } = req.body;
    if (!old_password || !new_password) return res.json(fail('请填写旧密码和新密码'));
    const user = get('SELECT * FROM users WHERE id=?', [req.adminId]);
    if (!user || !await bcrypt.compare(old_password, user.password)) {
      return res.json(fail('旧密码错误'));
    }
    const hash = bcrypt.hashSync(new_password, 10);
    run('UPDATE users SET password=? WHERE id=?', [hash, req.adminId]);
    return res.json(success(null, '密码修改成功'));
  } catch (e) { return res.json(fail('密码修改失败')); }
});

module.exports = { router, demoSafeGuard };
