"use client";

import { App } from "@capacitor/app";
import { Browser } from "@capacitor/browser";
import { loadUpdateManifest } from "@/lib/update/app-update-manifest";
import { updateLinkFor } from "@/lib/update/native/policy";
import type { AppInfo } from "../app-info";
import { defaultStoreLink, type StoreLink } from "../channels";
import type { OpenExternalOptions, PlatformServices } from "../services";
import { RangookApp, isRangookAppAvailable } from "./rangook-app";
import { beginPayment } from "./payment-return";

// Brand pink, for the browser tab the payment gateway opens in.
const TOOLBAR_COLOR = "#B44A32";

/** The app implementations of src/lib/platform/services.ts. */
export function createNativeServices(info: AppInfo): PlatformServices {
    const headers = appHeaders(info);

    const openExternal = async (url: string, options?: OpenExternalOptions): Promise<boolean> => {
        if (await open(url, options)) return true;
        if (options?.fallbackUrl) return open(options.fallbackUrl);
        return false;
    };

    return {
        openExternal,

        async startPayment(gatewayUrl, returnTo) {
            beginPayment(returnTo);
            // A browser tab over the app, which keeps its state; the backend returns via deep link.
            await Browser.open({ url: gatewayUrl, toolbarColor: TOOLBAR_COLOR });
        },

        requestHeaders() {
            return headers;
        },

        async openAppSettings() {
            if (!isRangookAppAvailable()) return false;
            try {
                const { opened } = await RangookApp.openAppSettings();
                return opened;
            } catch {
                return false;
            }
        },

        async openAppUpdatePage() {
            const link = await updateLink(info);
            if (!link) return false;
            return openExternal(link.url, { package: link.package, fallbackUrl: link.fallbackUrl });
        },

        onResume(listener) {
            const handle = App.addListener("resume", listener);
            return () => {
                handle.then((h) => h.remove()).catch(() => { });
            };
        },
    };
}

async function open(url: string, options?: OpenExternalOptions): Promise<boolean> {
    if (isRangookAppAvailable()) {
        try {
            const { opened } = await RangookApp.openExternal({ url, package: options?.package });
            return opened;
        } catch {
            return false;
        }
    }

    // No plugin (iOS for now): Capacitor hands foreign URLs to the OS.
    window.location.href = url;
    return true;
}

/** The manifest's update link for this channel, or the store page without a manifest. */
async function updateLink(info: AppInfo): Promise<StoreLink | null> {
    if (info.platform !== "android" && info.platform !== "ios") return null;

    const manifest = await loadUpdateManifest();
    const release = manifest?.[info.platform][info.channel];
    const appId = manifest?.appId ?? info.native?.applicationId;
    if (!appId) return null;

    return release ? updateLinkFor(release, info.channel, appId) : defaultStoreLink(info.channel, appId);
}

/** Sent with every API request from the apps, so the backend can tell them apart. */
function appHeaders(info: AppInfo): Record<string, string> {
    const headers: Record<string, string> = {
        "X-App-Platform": info.platform,
        "X-App-Channel": info.channel,
        "X-App-Web-Version": info.webVersion,
    };

    if (info.native) {
        headers["X-App-Version"] = info.native.version;
        headers["X-App-Build"] = String(info.native.build);
    }

    return headers;
}
