const express = require('express');
const prisma = require('../lib/prisma');
const { hashPassword, verifyPassword, signToken, authMiddleware } = require('../lib/auth');

const router = express.Router();

// 注册
router.post('/register', async (req, res) => {
  try {
    const { account, password } = req.body;
    if (!account || !password) {
      return res.status(400).json({ error: '账号和密码不能为空' });
    }
    if (password.length < 6) {
      return res.status(400).json({ error: '密码至少 6 位' });
    }

    const existing = await prisma.user.findUnique({ where: { account } });
    if (existing) {
      return res.status(409).json({ error: '该账号已注册' });
    }

    const user = await prisma.user.create({
      data: {
        account,
        password: hashPassword(password),
        libraryName: '我的角色库',
      },
    });

    const token = signToken(user.id);
    res.json({
      token,
      user: {
        id: user.id,
        account: user.account,
        isCreator: user.isCreator,
        creatorName: user.creatorName,
        libraryName: user.libraryName,
      },
    });
  } catch (err) {
    console.error('注册失败:', err);
    res.status(500).json({ error: '注册失败，请稍后重试' });
  }
});

// 登录
router.post('/login', async (req, res) => {
  try {
    const { account, password } = req.body;
    if (!account || !password) {
      return res.status(400).json({ error: '账号和密码不能为空' });
    }

    const user = await prisma.user.findUnique({ where: { account } });
    if (!user || !verifyPassword(password, user.password)) {
      return res.status(401).json({ error: '账号或密码错误' });
    }

    const token = signToken(user.id);
    res.json({
      token,
      user: {
        id: user.id,
        account: user.account,
        isCreator: user.isCreator,
        creatorName: user.creatorName,
        libraryName: user.libraryName,
      },
    });
  } catch (err) {
    console.error('登录失败:', err);
    res.status(500).json({ error: '登录失败，请稍后重试' });
  }
});

// 获取当前用户信息
router.get('/me', authMiddleware, async (req, res) => {
  try {
    const user = await prisma.user.findUnique({
      where: { id: req.userId },
      select: {
        id: true,
        account: true,
        isCreator: true,
        creatorName: true,
        libraryName: true,
        boundCreator: true,
      },
    });
    if (!user) {
      return res.status(404).json({ error: '用户不存在' });
    }
    res.json({ user });
  } catch (err) {
    console.error('获取用户信息失败:', err);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 更新用户设置
router.put('/settings', authMiddleware, async (req, res) => {
  try {
    const { creatorName, libraryName, isCreator } = req.body;
    const user = await prisma.user.update({
      where: { id: req.userId },
      data: {
        ...(creatorName !== undefined && { creatorName }),
        ...(libraryName !== undefined && { libraryName }),
        ...(isCreator !== undefined && { isCreator }),
      },
      select: {
        id: true,
        account: true,
        isCreator: true,
        creatorName: true,
        libraryName: true,
      },
    });
    res.json({ user });
  } catch (err) {
    console.error('更新设置失败:', err);
    res.status(500).json({ error: '更新失败' });
  }
});

module.exports = router;
