/**
 *
 * @param {any} str
 */
function log(str) {
    console.log(JSON.stringify(str, undefined, 4))
}

/**
 * clear SSR cache – entry-level invalidation
 *
 * Dependencies are stored as strings: "col:id" (detail) or "col:*" (list).
 * - POST (new entry):   only list deps affected → delete where "col:*"
 * - PUT/DELETE (entry):  detail + list deps affected → delete where "col:id" OR "col:*"
 * - No args:             full wipe (manual clear)
 *
 * @param {string} [collectionName] - collection name
 * @param {string} [entryId] - specific entry ID (for PUT/DELETE)
 * @param {string} [method] - HTTP method (POST/PUT/DELETE)
 * @returns {number}
 */
function clearSSRCache(collectionName, entryId, method) {
    /** @type {any} */
    let filter = {}
    const m = method ? method.toUpperCase() : ""

    if (collectionName && entryId && (m === "PUT" || m === "DELETE")) {
        // entry updated or deleted: invalidate pages that reference this specific entry OR list this collection
        filter = {
            $or: [{ dependencies: collectionName + ":" + entryId }, { dependencies: collectionName + ":*" }],
        }
    } else if (collectionName) {
        // new entry (POST) or unknown method: invalidate all pages that list this collection
        filter = { dependencies: collectionName + ":*" }
    }
    // else: no args → full wipe (empty filter)

    // @ts-ignore – filter uses MongoDB operators not in DbReadOptions type
    const info = context.db.deleteMany("ssr", { filter: filter })
    context.response.header("X-SSR-Cleared", info.removed)
    if (collectionName) {
        context.response.header("X-SSR-Cleared-Collection", collectionName)
    }
    return info.removed
}

module.exports = {
    log,
    clearSSRCache,
}
