const express = require('express');
const bcrypt = require('bcryptjs');
const db = require('../db/init');
const { generateToken } = require('../middleware/auth');
const { authLimiter } = require('../middleware/rateLimiter');
const { validate, registerRules, loginRules } = require('../middleware/validate');
const logger = require('../services/logger');

const router = express.Router();

// 注册
router.post('/register', authLimiter, registerRules, validate, (req, res) => {
  const { username, password } = req.body;

  try {
    const hashedPassword = bcrypt.hashSync(password, 10);
    const stmt = db.prepare('INSERT INTO users (username, password) VALUES (?, ?)');
    const result = stmt.run(username, hashedPassword);

    const user = { id: result.lastInsertRowid, username };
    const token = generateToken(user);

    logger.info(`用户注册成功: ${username}`);
    res.json({ user, token });
  } catch (err) {
    if (err.code === 'SQLITE_CONSTRAINT_UNIQUE') {
      return res.status(400).json({ error: '用户名已存在' });
    }
    logger.error('注册失败', { error: err.message });
    res.status(500).json({ error: '注册失败' });
  }
});

// 登录
router.post('/login', authLimiter, loginRules, validate, (req, res) => {
  const { username, password } = req.body;

  const stmt = db.prepare('SELECT * FROM users WHERE username = ?');
  const user = stmt.get(username);

  if (!user || !bcrypt.compareSync(password, user.password)) {
    logger.warn(`登录失败: ${username}`);
    return res.status(401).json({ error: '用户名或密码错误' });
  }

  const token = generateToken(user);
  logger.info(`用户登录成功: ${username}`);
  res.json({ user: { id: user.id, username: user.username }, token });
});

module.exports = router;
