"use client";

// Build identity, and the URL stamp derived from it.
//
// Everything else in this folder answers "am I running the current build?".
// This file answers "what build am I, and how do I say so in a URL?".

export { APP_VERSION, BUILD_ID } from "@/constants/version.constant";

import { BUILD_ID } from "@/constants/version.constant";

/**
 * The query param that scopes a URL to a build.
 *
 * WHY IT EXISTS
 *
 * In `output: export`, a client-side navigation fetches that route's RSC
 * payload, and Next derives the payload URL from the navigation URL by
 * appending to its pathname (see fetch-server-response.js):
 *
 *     /course/detail/?id=45   ->   /course/detail/index.txt?id=45
 *
 * It does `new URL(url)` and only touches `pathname`, so QUERY PARAMS ARE
 * PRESERVED -- which means a build stamp on the navigation URL lands on the
 * payload URL too, giving every build its own cache key for every payload. A
 * payload cached by an older build can then never be served to this one: the
 * URL has simply never been requested. Pages Router gets this for free from
 * /_next/data/{buildId}/...; App Router in export mode does not.
 *
 * Cache headers make staleness unlikely. A build-scoped URL makes it
 * impossible. `deploymentId` (next.config.ts) covers the other half by
 * stamping ?dpl= onto asset URLs: _r scopes payloads, dpl scopes assets.
 */
export const BUILD_ID_PARAM = "_r";

// Only stamp same-origin, in-app paths. Anything with a URI scheme
// (http:, https:, mailto:, tel:, ...) is off-app and must be left alone, as
// must bare "#" hashes and empty hrefs, which are placeholder/JS-driven
// controls rather than real navigation.
export function isInternalPath(href: string): boolean {
    if (!href) return false;
    if (href.startsWith("#")) return false;
    if (/^[a-z][a-z0-9+.-]*:/i.test(href)) return false; // any "scheme:" prefix
    if (href.startsWith("//")) return false; // protocol-relative
    return true;
}

/**
 * Appends/overwrites `_r` on an internal href, preserving existing query
 * params and hash. External links, hashes and empty hrefs pass through.
 *
 * Not in the apps: no HTTP cache there. Not in `next dev` either, where the
 * id would be the last release's (see isDevBuild) and the only visible effect
 * is a stale build id on every URL in the address bar.
 */
export function withBuildId(href: string): string {
    if (process.env.NEXT_PUBLIC_APP_TARGET === "native") return href;
    if (isDevBuild()) return href;
    if (!isInternalPath(href)) return href;

    const hashIndex = href.indexOf("#");
    const hash = hashIndex >= 0 ? href.slice(hashIndex) : "";
    const withoutHash = hashIndex >= 0 ? href.slice(0, hashIndex) : href;

    const queryIndex = withoutHash.indexOf("?");
    const path = queryIndex >= 0 ? withoutHash.slice(0, queryIndex) : withoutHash;
    const query = queryIndex >= 0 ? withoutHash.slice(queryIndex + 1) : "";

    const params = new URLSearchParams(query);
    params.set(BUILD_ID_PARAM, BUILD_ID);

    return `${path}?${params.toString()}${hash}`;
}

/** Same as withBuildId, for next/link's href which also accepts a UrlObject. */
export function withBuildIdUrl<T extends string | object>(href: T): T {
    if (process.env.NEXT_PUBLIC_APP_TARGET === "native") return href;
    if (isDevBuild()) return href;
    if (typeof href === "string") {
        return withBuildId(href) as T;
    }

    const obj = href as { pathname?: string; query?: Record<string, unknown>; hash?: string };
    if (!obj.pathname || !isInternalPath(obj.pathname)) return href;

    return {
        ...obj,
        query: { ...(obj.query ?? {}), [BUILD_ID_PARAM]: BUILD_ID },
    } as T;
}

/**
 * True in `next dev`.
 *
 * NOT "BUILD_ID === dev". Every build writes NEXT_PUBLIC_BUILD_ID into
 * .env.local (scripts/generate-version.js) and that file is kept afterwards,
 * so the next `next dev` inherits the last release's build id and the "dev"
 * fallback in version.constant.ts never applies. The whole update system then
 * runs against the dev server, which stamps ?dpl= on nothing: every chunk
 * reads as foreign, the tab force-reloads until the budget is spent, and the
 * console ends on "[update] stuck".
 *
 * NODE_ENV cannot be inherited that way. Next's DefinePlugin inlines it from
 * the compiler mode -- "development" for `next dev`, "production" for
 * `next build` -- never from .env.local, which is why the NODE_ENV line in
 * .env.local does not reach the bundle either. Being a literal, it also lets
 * webpack drop every dev-only branch from a production build.
 *
 * BUILD_ID is still checked, so a build that somehow runs without a generated
 * id is treated as dev rather than compared against a server it cannot match.
 */
export function isDevBuild(): boolean {
    return process.env.NODE_ENV !== "production" || BUILD_ID === "dev";
}
