
class UserAuthController {
    constructor() {
        this._config = undefined;
        this._secret_key = "config_secret_key";
        this._jwt = require('jsonwebtoken');
    }
    Set_Config(config) {
        this._config = config;
        this._secret_key = this._config.secret_key;
    }
    get_cookie_to_user_id(req) {
        let parse_cookie = this._parseJwt(req.cookies[this._config.cookie_name]);
        let ret_id = "";
        if (parse_cookie) ret_id = parse_cookie.id;
        return ret_id;
    }
    _parseJwt(token) {
        const base64Url = token.split('.')[1]; // payload 부분
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(
            atob(base64)
                .split('')
                .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
                .join('')
        );
        return JSON.parse(jsonPayload); // JSON 객체로 반환
    }
    regist_cookie(res, userInfo) {
        let jwtToken = this.generateJWTToken(userInfo);
        res.cookie(this._config.cookie_name, jwtToken, 
            { 
                httpOnly: true,
                // secure: true,
                sameSite: 'Strict' 
            }
        );
    }
    refresh_cookie_token(res, token) {
        res.cookie(this._config.cookie_name, token, 
            { 
                httpOnly: true,
                // secure: true,
                sameSite: 'Strict' 
            }
        );
    }
    generateJWTToken(user) {
        return this._jwt.sign(
            { 
                id: user.id,
                pw: user.pw
            }, 
            this._secret_key, 
            { 
                expiresIn: '1h' 
            }
        );
    }
    jwtTokenAuthentication(req, res, success, error) {
        try {
            let _cookie_token = req.cookies[this._config.cookie_name];
            if (_cookie_token != undefined) {
                console.log('요청한 토큰 ', _cookie_token);
                this._jwt.verify(_cookie_token, this._secret_key, (err, user) => {
                    if (err) {
                        if (err.name === 'TokenExpiredError') {
                            err.message = '토큰 만료';
                            err.statusCode = 401;
                        }
                        else {
                            err.message = '유효하지 않은 토큰';
                            err.statusCode = 403;
                        }
                        if (error) error(err);
                    }
                    else {
                        //token
                        let refresh_token = this.generateJWTToken(user);
                        this.refresh_cookie_token(res, refresh_token);
                        if (success) success();
                    }
                });
            }
            else {
                // 토큰 없어도 사용할 수 있도록 임시 오픈
                // if (success) success();
                throw new Error("유효하지 않은 토큰");
            }
        }
        catch(err) {
            err.statusCode = 403;
            if (error) error(err);
        }
    }
}

module.exports = UserAuthController;