const { apiSsrBaseURL } = require("../config")

/**
 * api request via server, cache result in context.ssrCache
 * should be elimated in client code via tree shaking
 *
 * @param {string} cacheKey
 * @param {string} endpoint
 * @param {string} query
 * @param {ApiOptions} options
 * @returns {ApiResult<any>}
 */
function ssrRequest(cacheKey, endpoint, query, options) {
    let url = endpoint + (query ? "?" + query : "")

    // console.log("############ FETCHING ", apiSsrBaseURL + url)

    const response = context.http.fetch(apiSsrBaseURL + url, {
        method: options.method,
        headers: options.headers,
    })

    // console.log(JSON.stringify(response.headers, null, 2))

    const json = response.body.json()
    const count = parseInt(response.headers["X-Results-Count"] || "0")

    // json is go data structure and incompatible with js, so we need to convert it
    const r = { data: JSON.parse(JSON.stringify(json)), count: count }

    // @ts-ignore
    context.ssrCache[cacheKey] = r
    return r
}
/**
 * api request via server, cache result in context.ssrCache
 * for BigCommerce requests, using context.http.fetch
 *
 * @param {string} cacheKey
 * @param {string} endpoint
 * @param {string} query
 * @param {ApiOptions} options
 * @returns {{status: number, body: any}}
 */
function ssrRequestBigCommerce(cacheKey, endpoint, query, options) {
    const response = context.http.fetch(endpoint, {
        method: options.method,
        headers: options.headers,
        body: options.body ? JSON.stringify(options.body) : undefined,
    })
    if (response.status >= 300) {
        console.log("SSR ERROR?!?!?!", response.status, JSON.stringify(response))
        return { status: response.status, body: { data: {}, count: 0 } }
    }

    const count = parseInt(response.headers["X-Results-Count"] || "0")
    const json = response.body.json()
    const result = { status: response.status, body: JSON.parse(JSON.stringify(json)), count: count }

    // @ts-ignore
    context.ssrCache[cacheKey] = result
    return result
}
module.exports = {
    ssrRequest,
    ssrRequestBigCommerce,
}
