//POST
const loginCtr = (req, res) => {
    let _resp_json = {
        result: "ok",
        reason: "",
        data: {},
        req_body: {},
        req_param: {}
    }
    if (req.body) {
        //id pw 체크하고, isApprove인지 확인
        let { id, pw } = 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;
        }

        _SPM.db.pgSql.Query_AUTH_CHECK_LOGIN(id)
        .then((resRow)=>{
            if (!resRow.rows.length) throw new Error("id is Empty");
            let rowObj = resRow.rows[0];
            if (!rowObj.isApprove) {
                _resp_json.result = "fail";
                // _resp_json.data = resRow.rows
                _resp_json.reason = 'is not approved id, tell the administrator';
                res.status(401).json(_resp_json);
            }
            else {
                if (rowObj.pw != pw) {
                    _GTP.BCRYPT_COMPARE(pw, rowObj.pw)
                    .then((hashRes)=>{
                        if (!hashRes) throw new Error("password is not matched");

                        //#region 쿠키 확인
                        let accInfo = {
                            id: id,
                            pw: rowObj.pw // 해쉬된 pw를 등록
                        };
                        _SPM.uac.regist_cookie(res, accInfo);
                        //#endregion

                        _resp_json.result = "ok";
                        _resp_json.data = {
                            isApproved: hashRes
                        };
                        _resp_json.reason = 'success';
                        res.status(200).json(_resp_json);
                    })
                    .catch((error)=>{
                        _resp_json.result = "fail";
                        _resp_json.reason = `password error, ${error.message}`;
                        res.status(401).json(_resp_json);
                    })
                }
            }
        })
        .catch((error)=>{
            _resp_json.result = "fail";
            _resp_json.reason = `login error, ${error.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 = loginCtr;