const express = require('express');
const bcrypt = require('bcryptjs');
const db = require('../config/database');
const { generateToken } = require('../middleware/auth');
const { asyncHandler, AppError } = require('../middleware/errorHandler');

const router = express.Router();

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

  if (!username || !password) {
    throw new AppError('请填写用户名和密码', 400, 'MISSING_FIELDS');
  }

  if (username.length < 3 || username.length > 20) {
    throw new AppError('用户名需3-20个字符', 400, 'INVALID_USERNAME');
  }

  if (password.length < 6 || password.length > 20) {
    throw new AppError('密码需6-20个字符', 400, 'INVALID_PASSWORD');
  }

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

  const token = generateToken(result.lastInsertRowid);
  console.log(`User registered: ${username}`);

  res.json({ token, username });
}));

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

  if (!username || !password) {
    throw new AppError('请填写用户名和密码', 400, 'MISSING_FIELDS');
  }

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

  if (!user) {
    throw new AppError('用户名或密码错误', 400, 'INVALID_CREDENTIALS');
  }

  const validPassword = await bcrypt.compare(password, user.password);
  if (!validPassword) {
    throw new AppError('用户名或密码错误', 400, 'INVALID_CREDENTIALS');
  }

  const token = generateToken(user.id);
  console.log(`User logged in: ${username}`);

  res.json({ token, username: user.username });
}));

module.exports = router;
