import type { AppInfo } from "@/lib/platform/app-info";
import { defaultStoreLink, type DistributionChannel, type StoreLink } from "@/lib/platform/channels";
import type { ChannelRelease, UpdateManifest } from "../app-update-manifest";

// Pure decision (no I/O): what the user sees for this build and manifest.

export interface UpdateOffer {
    channel: DistributionChannel;
    latestVersion: string;
    latestBuild: number;
    notes: string[];
    link: StoreLink;
}

export type UpdateDecision =
    | { kind: "none" }
    | { kind: "optional"; offer: UpdateOffer }
    | { kind: "required"; offer: UpdateOffer };

export const NO_UPDATE: UpdateDecision = { kind: "none" };

export function decideUpdate(info: AppInfo, manifest: UpdateManifest): UpdateDecision {
    if (!info.native) return NO_UPDATE;
    if (info.platform !== "android" && info.platform !== "ios") return NO_UPDATE;

    const release = manifest[info.platform][info.channel];
    if (!release) return NO_UPDATE;

    // No prompt without somewhere to send the user.
    const link = updateLinkFor(release, info.channel, manifest.appId);
    if (!link) return NO_UPDATE;

    const offer: UpdateOffer = {
        channel: info.channel,
        latestVersion: release.latestVersion,
        latestBuild: release.latestBuild,
        notes: release.notes,
        link,
    };

    const installed = info.native.build;
    if (installed < release.minimumBuild) return { kind: "required", offer };
    if (installed < release.latestBuild) return { kind: "optional", offer };
    return NO_UPDATE;
}

/** The manifest's own link for the channel, else the store's standard deep link. */
export function updateLinkFor(release: ChannelRelease, channel: DistributionChannel, appId: string): StoreLink | null {
    const standard = defaultStoreLink(channel, appId);

    if (release.url) {
        return {
            url: release.url,
            package: release.package ?? (release.url === standard?.url ? standard.package : undefined),
            fallbackUrl: release.fallbackUrl ?? standard?.fallbackUrl,
        };
    }

    if (!standard) return null;
    return { ...standard, fallbackUrl: release.fallbackUrl ?? standard.fallbackUrl };
}
