"use client";

import { BUILD_ID, BUILD_ID_PARAM } from "./identity";
import { buildStamp, claimAttempt, type BudgetName } from "./budget";

const CACHE_CLEAR_TIMEOUT_MS = 2000;
const RELOAD_DELAY_MS = 300;

let reloadScheduled = false;

/**
 * Has a reload already been committed in this tab?
 *
 * Once location.replace() is called the browser aborts every request still in
 * flight, and an aborted <script> fires an error event exactly like a real
 * 404 does. Anything watching for chunk failures must be able to tell those
 * apart, or our own recovery reload looks like a burst of new failures and
 * re-triggers recovery.
 */
export function isReloadScheduled(): boolean {
    return reloadScheduled;
}

/**
 * Drop what this app controls, then reload onto a URL no cache has seen.
 *
 * replace() rather than assign() so no history entry is added and the back
 * button is not trapped. Reusing `_r` rather than inventing a second param
 * means the reload lands pre-stamped with the right build and there is
 * nothing to strip afterwards.
 *
 * @param budget which attempt budget to spend -- see budget.ts
 * @param target the build being aimed at; also what the budget is keyed on
 * @returns true if a reload is under way, false if the budget is spent.
 *          On false the caller must NOT reload by other means.
 */
export async function hardReload(budget: BudgetName, target: string): Promise<boolean> {
    if (reloadScheduled) return true;

    const attempt = claimAttempt(budget, target);

    if (attempt === null) {
        console.error(
            `[update] stuck: running ${BUILD_ID}, wanted ${target}, ` +
            `retries exhausted and the problem persists`
        );
        return false;
    }

    reloadScheduled = true;

    // PAST THIS POINT THE RELOAD MUST HAPPEN.
    //
    // reloadScheduled is already true and an attempt is already spent, so an
    // exception escaping between here and location.replace() does not just
    // skip the cache clear -- it wedges the tab. isReloadScheduled() would
    // answer true forever, making every later version check and every chunk
    // recovery a no-op, with the budget consumed and no reload performed.
    // Silent, permanent, and indistinguishable from "everything is fine".
    //
    // dropCaches() catches internally and delay() cannot reject, so nothing
    // here is expected to throw. That is exactly the assumption worth not
    // betting the recovery path on: the cost of being wrong is total, and the
    // cost of the try/catch is nothing.
    try {
        // Awaited, not fire-and-forget: an earlier version kicked off an async
        // cache clear and reloaded on a timer, so the two raced. Bounded so a
        // hung Cache Storage call cannot strand the user here.
        await Promise.race([dropCaches(), delay(CACHE_CLEAR_TIMEOUT_MS)]);
        await delay(RELOAD_DELAY_MS);
    } catch (err) {
        // Reloading on a not-fully-cleared cache still beats not reloading:
        // the URL below is one no cache has seen either way.
        console.warn("[update] pre-reload cleanup failed, reloading anyway:", err);
    }

    try {
        const url = new URL(window.location.href);
        url.searchParams.set(BUILD_ID_PARAM, buildStamp(target, attempt));
        window.location.replace(url.toString());
    } catch {
        window.location.reload();
    }

    return true;
}

/**
 * Drops Cache Storage and nudges the service worker to update.
 *
 * DOES NOT unregister the service worker. An earlier version did, which was
 * safe only while the app had no service worker of its own -- the moment one
 * ships, unregistering on every repair would destroy the very thing that
 * guarantees fresh documents, and do it precisely when the app is already in
 * trouble. Updating is what we want: same registration, new script.
 *
 * DOES NOT touch localStorage. Clearing it was a blunt instrument that wiped
 * unrelated user state.
 */
async function dropCaches(): Promise<void> {
    try {
        // Cache Storage entries are all rebuildable from the network, and the
        // worker repopulates them on the next load.
        if (typeof caches !== "undefined") {
            const names = await caches.keys();
            await Promise.all(names.map((n) => caches.delete(n)));
        }
    } catch (err) {
        console.warn("[update] cache clear failed:", err);
    }

    try {
        if ("serviceWorker" in navigator) {
            const reg = await navigator.serviceWorker.getRegistration();
            if (reg) await reg.update();
        }
    } catch (err) {
        console.warn("[update] service worker update failed:", err);
    }
}

export function delay(ms: number): Promise<void> {
    return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
