
//POST
const createCtr = (req, res) => {
    let _resp_json = {
        result: "ok",
        reason: "",
        data: {},
        req_body: {},
        req_param: {}
    }

    if (req.body) {
        let { id, pw, name, pos, cls } = req.body;
        let ret_id = _GTP.STR_VALIDER(id);
        if (!ret_id) {
            _resp_json.result = "fail";
            _resp_json.reason = "Body 'id' Error";
            res.status(400).json(_resp_json);
            return;
        }

        let ret_pw = _GTP.STR_VALIDER(pw);
        if (!ret_pw) {
            _resp_json.result = "fail";
            _resp_json.reason = "Body 'pw' Error";
            res.status(400).json(_resp_json);
            return;
        }

        if (cls == undefined || cls == "") cls = "guest"

        _GTP.BCRYPT_HASH(pw).then((hashed) => {
            let _recvData = {
                id: id,
                pw: hashed,
                name: name,
                pos: pos,
                cls: cls
            } 

            //#region 계정 중복 제외
            _SPM.db.pgSql.Query_AUTH_IDCHECK(id)
            .then((resRow) => {
                console.log();
                let getDup = Number(resRow.rows[0].count);
                if (getDup) {
                    //중복 있으면, 
                    _resp_json.result = "fail";
                    _resp_json.reason = 'account already created';
                    res.status(400).json(_resp_json);
                }
                else {
                    //중복 아이디 없는경우 계정 생성
                    _SPM.db.pgSql.Query_AUTH_CREATE(_recvData)
                    .then((resRow) => {
                        _resp_json.result = "ok";
                        _resp_json.reason = 'account create';
                        res.status(200).json(_resp_json);
                    })
                    .catch((err) => {
                        _resp_json.result = "fail";
                        _resp_json.reason = `/auth/create query error, ${err.message}`;
                        res.status(500).json(_resp_json);
                    })
                }
            })
            .catch((err) => {
                _resp_json.result = "fail";
                _resp_json.reason = `/auth/create query error, ${err.message}`;
                res.status(500).json(_resp_json);
            })
            //#endregion

        })
        .catch((err)=>{
            _resp_json.result = "fail";
            _resp_json.reason = `create account error, ${err.message}`;
            res.status(500).json(_resp_json);
        })
    }
    else {
        //exception
        _resp_json.result = "fail";
        _resp_json.reason = 'Bad Request';
        res.status(400).json(_resp_json);
    }
}

module.exports = createCtr;