const API = require("../../lib/API");
const db = require("../../plugin/DataBase/db");
const { BaseStdResponse } = require("../../BaseStdResponse");
const AccessControl = require("../../lib/AccessControl");

class ChangeUsername extends API {
    constructor() {
        super();

        this.setMethod("POST");
        this.setPath("/User/ChangeUsername");
    }

    checkUsername(username) {
        const regex = /^[\u4e00-\u9fa5A-Za-z0-9]{3,8}$/;
        return regex.test(username);
    }

    async onRequest(req, res) {
        let { uuid, session, username } = req.body;

        if ([uuid, session, username].some(value => value === '' || value === null || value === undefined)) {
            return res.json({
                ...BaseStdResponse.MISSING_PARAMETER,
                endpoint: 1513126
            });
        }

        if (!this.checkUsername(username))
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '用户名需在3到8位之间，且只能含有英文字母和汉字'
            })

        // 检查 session 是否有效
        if (!await AccessControl.checkSession(uuid, session)) {
            return res.status(401).json({
                ...BaseStdResponse.ACCESS_DENIED,
                endpoint: 48153145
            });
        }

        let sql = 'SELECT username FROM users WHERE username = ?';
        let UserRows = await db.query(sql, [username]);
        if (UserRows.length > 0)
            return res.json({
                ...BaseStdResponse.USER_ALREADY_EXISTS,
                msg: '该用户名已被占用！'
            })

        sql = 'UPDATE users SET username = ? WHERE uuid = ?';
        let result = await db.query(sql, [username, uuid]);
        if (!result || result.affectedRows !== 1)
            return res.json({
                ...BaseStdResponse.ERR,
                msg: '更新用户名失败'
            });

        res.json({
            ...BaseStdResponse.OK
        });
    }
}

module.exports.ChangeUsername = ChangeUsername;
