const apiSsrBaseURL =
    "http://localhost:" + context.config.server().api.port + "/api/v1/_/" + context.api().namespace + "/"

const now = { $date: new Date().toISOString() }
const publishedFilter = {
    active: true,
    $or: [
        { publication: { $exists: false } },
        { publication: null },
        {
            $and: [
                {
                    $or: [
                        { "publication.from": { $exists: false } },
                        { "publication.from": null },
                        { "publication.from": { $lte: now } },
                    ],
                },
                {
                    $or: [
                        { "publication.to": { $exists: false } },
                        { "publication.to": null },
                        { "publication.to": { $gte: now } },
                    ],
                },
            ],
        },
    ],
}

module.exports = {
    apiSsrBaseURL,
    publishedFilter,
    ssrValidatePath: function (/** @type {string} */ path) {
        // validate if path ssr rendering is ok, -1 = NOTFOUND, 0 = NO SSR, 1 = SSR
        // Starter project: SSR the app shell for language roots and all published content pages.
        if (path === "/" || path.match(/^\/(de|en)\/?$/)) {
            return 1
        }

        const langMatch = path.match(/^\/(de|en)(\/|$)/)
        const lang = langMatch ? langMatch[1] : null
        const routePath = lang ? path.replace(/^\/(de|en)(?=\/|$)/, "") || "/" : path

        const resp = context.db.find("content", {
            filter: {
                $and: [
                    ...(lang ? [{ lang: lang }] : []),
                    { $or: [{ path: routePath }, { "alternativePaths.path": routePath }] },
                    publishedFilter,
                ],
            },
            selector: { _id: 1, path: 1, lang: 1 },
        })
        if (resp && resp.length) {
            const canonicalLang = resp[0].lang || lang
            const canonicalPath = resp[0].path || routePath
            const canonicalUrl = canonicalLang
                ? `/${canonicalLang}${canonicalPath === "/" ? "" : canonicalPath}`
                : canonicalPath

            if (canonicalUrl && canonicalUrl !== path) {
                return canonicalUrl
            }
            return 1
        }

        return -1
    },
    ssrPublishCheckCollections: ["content"],
}
