const { apiSsrBaseURL, ssrPublishCheckCollections } = 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 : "")

    if (ssrPublishCheckCollections.includes(endpoint)) {
        // @ts-ignore
        let validUntil = context.ssrCacheValidUntil

        // check in db for publish date to invalidate cache
        const _optionsPublishSearch = Object.assign(
            {},
            { filter: options?.filter },
            {
                selector: { publishDate: 1 },
                // projection: null,
            }
        )
        const publishSearch = context.db.find(endpoint, _optionsPublishSearch)
        publishSearch?.forEach((item) => {
            const publishDate = item.publishDate ? new Date(item.publishDate.unixMilli()) : null

            if (publishDate && publishDate > new Date()) {
                // entry has a publish date in the future, set global validUntil
                if (validUntil == null || validUntil > publishDate) {
                    validUntil = publishDate
                }
            }
        })
        // @ts-ignore
        context.ssrCacheValidUntil = validUntil
    }

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

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

    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
}

module.exports = {
    ssrRequest,
}
