const Config = require("./Config")
    , fetch = require('node-fetch')
    , crypto = require('crypto');

class Request extends Config {

    constructor() {
        super()
        this.baseUrl = 'https://api-gateway.coupang.com';
    }

    getHeaders(method, path) {    
        path = path.replace('?', '')    
        let authorization = "CEA algorithm=HmacSHA256, access-key=" + this.accessKey + ", signed-date=" + this.datetime + ", signature="
            + crypto.createHmac('sha256', this.secretKey).update(this.datetime + method + path).digest('hex');
        return {
            method: method,
            "Content-Type": "application/json;charset=UTF-8",
            "Authorization": authorization
        }
    }

    getQuery(obj) {
        var str = [];
        for (var p in obj)
            if (obj.hasOwnProperty(p)) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
        return str.join("&");
    }

    request(params) {
        return fetch(this.baseUrl + params.path, {method:params.method, headers: this.getHeaders(params.method, params.path), body: params.body })
            .then(res => res.text()).then(json => JSON.parse(json));
    }
    

}


module.exports = Request