"use client";

import { App } from "@capacitor/app";
import { getAppInfo } from "@/lib/platform/app-info";
import { getPlatformServices } from "@/lib/platform/services";
import { loadUpdateManifest } from "../app-update-manifest";
import { decideUpdate, type UpdateOffer } from "./policy";
import { applyDecision, getNativeUpdateState } from "./state";

// App updates, from public/app-update.json, each copy sent to its own store:
//   latestBuild   newer than installed  ->  dismissible prompt (24 h snooze)
//   minimumBuild  newer than installed  ->  blocking screen until updated

// Re-check on resume at most this often; a required update is re-checked on every resume.
const RESUME_RECHECK_MS = 30 * 60 * 1000;

let lastCheckAt = 0;
let inFlight: Promise<void> | null = null;
let started = false;

/** From the native bootstrap, once the binary's build info is known. */
export function startNativeUpdates(): void {
    if (started) return;
    started = true;

    void checkForNativeUpdate();

    App.addListener("resume", () => {
        const overdue = Date.now() - lastCheckAt > RESUME_RECHECK_MS;
        if (overdue || getNativeUpdateState().kind === "required") void checkForNativeUpdate();
    }).catch(() => { });
}

export function checkForNativeUpdate(): Promise<void> {
    if (inFlight) return inFlight;

    inFlight = (async () => {
        const manifest = await loadUpdateManifest();
        lastCheckAt = Date.now();

        // No manifest: keep whatever is showing.
        if (!manifest) return;

        applyDecision(decideUpdate(getAppInfo(), manifest));
    })().finally(() => {
        inFlight = null;
    });

    return inFlight;
}

/** Send the user to where their copy of the app updates. False if nothing opened. */
export function openUpdate(offer: UpdateOffer): Promise<boolean> {
    return getPlatformServices().openExternal(offer.link.url, {
        package: offer.link.package,
        fallbackUrl: offer.link.fallbackUrl,
    });
}
