const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = require('../db');
const { JWT_SECRET } = require('../middleware/auth');

const router = express.Router();

// POST /api/auth/login
router.post('/login', (req, res) => {
    const { username, password } = req.body;

    if (!username || !password) {
        return res.status(400).json({ code: 400, message: '用户名和密码不能为空' });
    }

    const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
    if (!user) {
        return res.status(401).json({ code: 401, message: '用户名或密码错误' });
    }

    if (user.status !== 1) {
        return res.status(403).json({ code: 403, message: '账号已被禁用' });
    }

    if (user.role === 'sales') {
        return res.status(403).json({ code: 403, message: '销售人员无需登录系统' });
    }

    if (!bcrypt.compareSync(password, user.password)) {
        return res.status(401).json({ code: 401, message: '用户名或密码错误' });
    }

    const token = jwt.sign(
        { id: user.id, username: user.username, role: user.role, realname: user.realname },
        JWT_SECRET,
        { expiresIn: '24h' }
    );

    res.json({
        code: 200,
        message: '登录成功',
        data: {
            token,
            user: {
                id: user.id,
                username: user.username,
                realname: user.realname,
                role: user.role
            }
        }
    });
});

// GET /api/auth/me
router.get('/me', (req, res) => {
    // This route requires authentication (handled in middleware)
    const user = db.prepare('SELECT id, username, realname, role, status FROM users WHERE id = ?').get(req.user.id);
    if (!user) {
        return res.status(404).json({ code: 404, message: '用户不存在' });
    }
    res.json({ code: 200, data: user });
});

module.exports = router;
