import { Router } from 'express';
import { body } from 'express-validator';
import { AuthService } from '../services/AuthService.js';
import { authenticate } from '../middleware/auth.js';
import { asyncHandler } from '../middleware/error.js';
import { validateRequest } from '../middleware/validate.js';

const router = Router();
const authService = new AuthService();

// 获取注册配置（公开接口）
router.get('/config', (_req, res) => {
  // 环境变量优先，必须明确设置为 'true' 才开放注册
  const allowRegistration = process.env.ALLOW_REGISTRATION === 'true';
  res.json({
    success: true,
    data: {
      allowRegistration,
    },
  });
});

// 登录
router.post(
  '/login',
  [
    body('username').notEmpty().withMessage('用户名不能为空'),
    body('password').notEmpty().withMessage('密码不能为空'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const { username, password, rememberMe } = req.body;
    const ip = req.ip || req.socket.remoteAddress || '';
    const deviceInfo = req.headers['user-agent'] || '';
    
    const result = await authService.login(username, password, ip, deviceInfo, rememberMe);
    
    res.json({
      success: true,
      data: result,
    });
  })
);

// 注册
router.post(
  '/register',
  [
    body('username')
      .notEmpty().withMessage('用户名不能为空')
      .isLength({ min: 3, max: 50 }).withMessage('用户名长度为3-50个字符'),
    body('password')
      .notEmpty().withMessage('密码不能为空')
      .isLength({ min: 6 }).withMessage('密码长度至少6个字符'),
    body('email').optional().isEmail().withMessage('邮箱格式不正确'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const { username, password, email, nickname } = req.body;
    
    const result = await authService.register({ username, password, email, nickname });
    
    res.status(201).json({
      success: true,
      data: result,
    });
  })
);

// 刷新 Token
router.post(
  '/refresh',
  [
    body('refreshToken').notEmpty().withMessage('刷新令牌不能为空'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const { refreshToken } = req.body;
    
    const result = await authService.refreshToken(refreshToken);
    
    res.json({
      success: true,
      data: result,
    });
  })
);

// 退出登录
router.post(
  '/logout',
  authenticate,
  asyncHandler(async (req, res) => {
    const { refreshToken } = req.body;
    
    if (refreshToken) {
      await authService.logout(refreshToken);
    }
    
    res.json({
      success: true,
      message: '已退出登录',
    });
  })
);

// 获取当前用户信息
router.get(
  '/me',
  authenticate,
  asyncHandler(async (req, res) => {
    const user = await authService.getCurrentUser(req.user!.userId);
    
    res.json({
      success: true,
      data: user,
    });
  })
);

// 修改密码
router.put(
  '/password',
  authenticate,
  [
    body('oldPassword').notEmpty().withMessage('旧密码不能为空'),
    body('newPassword')
      .notEmpty().withMessage('新密码不能为空')
      .isLength({ min: 6 }).withMessage('新密码长度至少6个字符'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const { oldPassword, newPassword } = req.body;
    
    await authService.changePassword(req.user!.userId, oldPassword, newPassword);
    
    res.json({
      success: true,
      message: '密码修改成功',
    });
  })
);

// 更新个人资料
router.put(
  '/profile',
  authenticate,
  [
    body('nickname').optional().isLength({ max: 50 }).withMessage('昵称最多50个字符'),
    body('email').optional().isEmail().withMessage('邮箱格式不正确'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const { nickname, email, avatarUrl } = req.body;
    
    const user = await authService.updateProfile(req.user!.userId, { nickname, email, avatarUrl });
    
    res.json({
      success: true,
      data: user,
    });
  })
);

export default router;
