"use client";

import { BUILD_ID, isDevBuild } from "./identity";
import { clearBudget } from "./budget";
import { hardReload, isReloadScheduled } from "./reload";
import { healEntryPoints } from "./entry-points";
import { rearmLegacyCheck } from "./legacy";

// checkForUpdate() has several call sites -- mount, route change, focus,
// visibilitychange, a periodic timer, and chunk-error recovery -- and more
// than one can fire in the same tick. Without coordination each would
// independently see a mismatch and independently spend an attempt, burning
// the whole budget before a single reload happened.
let inFlight: Promise<boolean> | null = null;

/**
 * Is the build running in this tab still the one the server is serving?
 *
 * The comparison is BUILD_ID -- compiled into this bundle -- against
 * version.json. Never a marker in storage. The pre-2.2.8 implementation
 * wrote "I am on version X" to localStorage BEFORE the reload had succeeded,
 * so a client whose reload came back stale ended up with storage claiming it
 * was current while old code kept running, which disarmed the check
 * permanently (see legacy.ts). Reading BUILD_ID means a stale bundle
 * re-derives "I am stale" on every load and cannot talk itself out of it.
 *
 * @returns true if an update was found and a reload is under way.
 */
export function checkForUpdate(): Promise<boolean> {
    if (isReloadScheduled()) return Promise.resolve(true);
    if (inFlight) return inFlight;

    inFlight = runCheck().finally(() => {
        inFlight = null;
    });

    return inFlight;
}

async function runCheck(): Promise<boolean> {
    // `next dev` never runs generate-version.js, so there is no build identity
    // to compare against.
    if (isDevBuild()) return false;

    // Apps: version.json ships in the same bundle, so it always agrees.
    if (process.env.NEXT_PUBLIC_APP_TARGET === "native") return false;

    try {
        // no-store handles the browser; the timestamp handles any intermediary
        // that ignores it. version.json is tiny, so defeating every cache layer
        // costs nothing.
        const res = await fetch(`/version.json?t=${Date.now()}`, { cache: "no-store" });
        if (!res.ok) return false;

        const data = await res.json();

        // buildId is the per-build identity; version is the semver fallback
        // for a version.json old enough to predate buildId.
        const served = String(data?.buildId ?? data?.version ?? "");
        if (!served) return false;

        if (served === BUILD_ID) {
            clearBudget("version");

            // We are provably on the current build. That makes this the only
            // safe moment to do the two repairs that outlive this page:
            healEntryPoints();  // fix the cached copy of start_url
            rearmLegacyCheck(); // re-arm the old check for any old bundle

            return false;
        }

        return await hardReload("version", served);
    } catch (err) {
        console.warn("[update] check failed:", err);
        return false;
    }
}

/**
 * Force this tab onto a freshly fetched document when something is plainly
 * broken but the version check itself is satisfied.
 *
 * A bare location.reload() cannot do this job: it reloads the SAME URL, so
 * whatever cache handed us the broken document can hand back a byte-identical
 * copy. This goes through hardReload(), which drops caches and lands on a URL
 * no cache has seen -- the automated form of the "send them a link with a
 * junk query on it" rescue.
 */
export function forceReloadOntoCurrentBuild(): Promise<boolean> {
    if (isDevBuild()) return Promise.resolve(false);
    // Nothing in the apps is fetched from a server that a reload could fix.
    if (process.env.NEXT_PUBLIC_APP_TARGET === "native") return Promise.resolve(false);
    if (isReloadScheduled()) return Promise.resolve(true);

    // Keyed on BUILD_ID: stable across retries, so attempts accumulate rather
    // than resetting each time.
    return hardReload("force", BUILD_ID);
}

/**
 * Catches a chunk from a DIFFERENT deployment executing inside this one.
 *
 * checkForUpdate() only compares the shell against the server, so it is
 * satisfied whenever version.json matches BUILD_ID -- even while a stale
 * route payload has pulled in a page chunk from an older deploy. That mixed
 * state is invisible to a version comparison, and it is what users saw: the
 * current version on the profile screen, last season's behaviour on the
 * course screen.
 *
 * deploymentId (next.config.ts) stamps ?dpl=<buildId> onto every asset URL
 * Next emits, so a chunk's origin build is readable at runtime. Two things
 * count as foreign: a dpl that is not ours, and no dpl at all (the chunk
 * predates deploymentId, so it is old). The second is the one that bit us --
 * a chunk comparing purchase_status against the retired "complete" value,
 * still being pulled in by stale payloads under a current shell.
 *
 * Call it after a route has rendered, so its chunks have loaded.
 */
export async function checkBuildIntegrity(): Promise<boolean> {
    if (isDevBuild()) return false;
    // One bundle, one build: the apps cannot mix chunks from two deployments.
    if (process.env.NEXT_PUBLIC_APP_TARGET === "native") return false;
    if (isReloadScheduled()) return true;

    const foreign = findForeignChunk();
    if (!foreign) return false;

    console.warn(`[update] foreign chunk in build ${BUILD_ID}:`, foreign);

    return forceReloadOntoCurrentBuild();
}

function findForeignChunk(): string | null {
    try {
        const entries = performance.getEntriesByType("resource");

        for (const entry of entries) {
            const url = entry.name;

            if (!url.includes("/_next/static/")) continue;
            if (!/\.(js|mjs|css)(\?|$)/.test(url)) continue;

            const match = /[?&]dpl=([^&]+)/.exec(url);

            if (!match) return url;
            if (match[1] !== BUILD_ID) return url;
        }
    } catch { }

    return null;
}
