"use client";

import { APP_UPDATE_MANIFEST_URL } from "@/constants/connection.constant";
import { toChannel, type DistributionChannel } from "@/lib/platform/channels";

// public/app-update.json: the latest release per store. The apps read it for update
// prompts, the website for "get the app" links. Edit it with `npm run app-update`.
// Builds are compared as versionCode integers, never version strings.

export type NativePlatform = "android" | "ios";

export interface ChannelRelease {
    /** Shown to the user, e.g. "2.4.0". */
    latestVersion: string;
    /** versionCode of the newest build live on this channel. 0 = not published here yet. */
    latestBuild: number;
    /** Installed builds below this are blocked until they update. 0 = none. */
    minimumBuild: number;
    /** What changed, one line each, shown in the update prompt. */
    notes: string[];
    /** Where the update is: a store deep link, or the APK's URL. Default: the store's own deep link. */
    url?: string;
    /** Android: the app that must open `url` (a store). */
    package?: string;
    /** Browser page used when nothing can open `url`. Also the website's download link. */
    fallbackUrl?: string;
}

export interface UpdateManifest {
    schemaVersion: 1;
    /** Store identity the default store links are built from. */
    appId: string;
    android: Partial<Record<DistributionChannel, ChannelRelease>>;
    ios: Partial<Record<DistributionChannel, ChannelRelease>>;
}

/** Null if the file is unusable; a single bad channel is dropped, not the whole file. */
export function parseUpdateManifest(raw: unknown): UpdateManifest | null {
    if (!isObject(raw)) return null;
    if (raw.schemaVersion !== 1) return null;
    if (typeof raw.appId !== "string" || !raw.appId) return null;

    return {
        schemaVersion: 1,
        appId: raw.appId,
        android: parseChannels(raw.android, "android"),
        ios: parseChannels(raw.ios, "ios"),
    };
}

function parseChannels(raw: unknown, platform: NativePlatform): UpdateManifest["android"] {
    const result: UpdateManifest["android"] = {};
    if (!isObject(raw)) return result;

    for (const [key, value] of Object.entries(raw)) {
        const channel = toChannel(key);
        const release = parseRelease(value);

        if (channel === "unknown" || channel === "web" || !release) {
            console.warn(`[app-update] ignoring ${platform}.${key}: not a valid channel release`);
            continue;
        }
        result[channel] = release;
    }
    return result;
}

function parseRelease(raw: unknown): ChannelRelease | null {
    if (!isObject(raw)) return null;

    const { latestVersion, latestBuild, minimumBuild, notes, url, fallbackUrl } = raw;
    const pkg = raw.package;

    if (typeof latestVersion !== "string") return null;
    if (!isBuildNumber(latestBuild) || !isBuildNumber(minimumBuild)) return null;
    // A minimum above the latest would block users with no way to comply.
    if (minimumBuild > latestBuild) return null;
    if (notes !== undefined && !(Array.isArray(notes) && notes.every((n) => typeof n === "string"))) return null;
    if (url !== undefined && typeof url !== "string") return null;
    if (pkg !== undefined && typeof pkg !== "string") return null;
    if (fallbackUrl !== undefined && typeof fallbackUrl !== "string") return null;

    return {
        latestVersion,
        latestBuild,
        minimumBuild,
        notes: (notes as string[] | undefined) ?? [],
        url: url as string | undefined,
        package: pkg as string | undefined,
        fallbackUrl: fallbackUrl as string | undefined,
    };
}

function isBuildNumber(value: unknown): value is number {
    return typeof value === "number" && Number.isInteger(value) && value >= 0;
}

function isObject(value: unknown): value is Record<string, unknown> {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}

/** The manifest, or null on any failure; null means "no prompt", never a broken app. */
export async function loadUpdateManifest(): Promise<UpdateManifest | null> {
    try {
        let raw: unknown;

        if (process.env.NEXT_PUBLIC_APP_TARGET === "native") {
            // Native request: the server sends no CORS headers for static files.
            const { getJson } = await import("@/lib/platform/native/http");
            raw = await getJson(APP_UPDATE_MANIFEST_URL);
        } else {
            const res = await fetch(`/app-update.json?t=${Date.now()}`, { cache: "no-store" });
            if (!res.ok) return null;
            raw = await res.json();
        }

        const manifest = parseUpdateManifest(raw);
        if (!manifest) console.warn("[app-update] manifest rejected: wrong shape or schemaVersion");
        return manifest;
    } catch (err) {
        console.warn("[app-update] manifest unavailable:", err);
        return null;
    }
}
