"use client";

import { BUILD_ID, BUILD_ID_PARAM, isDevBuild } from "./identity";
import { checkForUpdate } from "./version-check";
import { initChunkErrorGuard } from "./chunk-errors";
import { registerServiceWorker } from "./service-worker";

// How often an already-open tab re-checks for a new deployment. A tab left
// open never remounts the app, so without this it would never notice a
// release until the user manually reloaded.
const POLL_INTERVAL_MS = 5 * 60 * 1000;

/**
 * The whole update system, in defence-in-depth order.
 *
 *   1. service worker   -- decides document freshness in code we ship, rather
 *                          than leaving it to the browser's HTTP cache.
 *                          The only layer that fixes a PWA cold start
 *                          properly. Absent on hostile/unsupported clients.
 *   2. _r stamping      -- gives every build its own cache key for every RSC
 *                          payload, so a stale payload cannot be served to a
 *                          new build even if a cache wanted to.
 *   3. version check    -- BUILD_ID vs version.json, on mount, route change,
 *                          focus, visibility and a timer.
 *   4. build integrity  -- catches a chunk from another deployment running
 *                          inside a current shell, which (3) cannot see.
 *   5. chunk recovery   -- catches assets that fail outright.
 *   6. entry-point heal -- repairs the cached copy of start_url so a fix
 *                          survives the browser being closed. Bridge until
 *                          (1) is installed everywhere.
 *   7. legacy re-arm    -- un-disarms the pre-2.2.8 check for clients still
 *                          running it.
 *
 * 6 and 7 run from inside the version check, at the one moment we can prove
 * we are on the current build.
 *
 * Web only: the apps update through their stores (src/lib/update/native/).
 *
 * @returns a teardown function for the listeners this installs.
 */
export function initUpdateSystem(): () => void {
    if (typeof window === "undefined") return () => { };
    if (process.env.NEXT_PUBLIC_APP_TARGET === "native") return () => { };

    // `next dev` has no deployed build to compare against, and HMR makes a
    // chunk 404 an ordinary event rather than a broken deploy. Gated here
    // rather than layer by layer because initChunkErrorGuard() has no check of
    // its own: left installed, every HMR rebuild would reach recover(), log
    // "giving up" and raise a Sentry event against the real project.
    if (isDevBuild()) return () => { };

    stampFirstUrl();
    registerServiceWorker();
    initChunkErrorGuard();

    // Covers a fresh load / new tab.
    checkForUpdate();

    const onVisible = () => {
        if (document.visibilityState === "visible") checkForUpdate();
    };
    const onFocus = () => { checkForUpdate(); };

    const interval = window.setInterval(() => { checkForUpdate(); }, POLL_INTERVAL_MS);
    document.addEventListener("visibilitychange", onVisible);
    window.addEventListener("focus", onFocus);

    return () => {
        window.clearInterval(interval);
        document.removeEventListener("visibilitychange", onVisible);
        window.removeEventListener("focus", onFocus);
    };
}

/**
 * Put `_r` on the very first URL of this tab.
 *
 * Internal <Link>s and router calls are stamped before the click, but a hard
 * load -- typed URL, external referrer, PWA cold start -- has no such moment,
 * and a static export has no server that could inject it into the response.
 * Without this the first client-side navigation away from this page would
 * derive an unstamped payload URL from an unstamped document URL.
 *
 * Rewriting in place is safe because this is the FIRST history entry the tab
 * has: there is no earlier SPA entry whose router state this could desync
 * from. history.state is preserved rather than nulled, which is what broke
 * back-button restoration in an earlier attempt.
 */
function stampFirstUrl(): void {
    if (isDevBuild()) return;

    try {
        const url = new URL(window.location.href);
        if (url.searchParams.has(BUILD_ID_PARAM)) return;

        url.searchParams.set(BUILD_ID_PARAM, BUILD_ID);
        window.history.replaceState(window.history.state, "", url.toString());
    } catch { }
}

export {
    APP_VERSION,
    BUILD_ID,
    BUILD_ID_PARAM,
    withBuildId,
    withBuildIdUrl,
    isDevBuild,
} from "./identity";

export { checkForUpdate, checkBuildIntegrity, forceReloadOntoCurrentBuild } from "./version-check";
export { isReloadScheduled } from "./reload";
export { unregisterServiceWorker } from "./service-worker";
