"use client";

import { Capacitor } from "@capacitor/core";
import { App } from "@capacitor/app";
import { Device } from "@capacitor/device";
import { setAuthValueStore } from "@/lib/services/auth.service";
import { setSentryAppContext } from "@/lib/sentry";
import { startNativeUpdates } from "@/lib/update/native";
import { getAppInfo, setAppInfo, type AppInfo, type NativeBinaryInfo } from "../app-info";
import { toChannel } from "../channels";
import { installPlatformServices } from "../services";
import { createNativeAuthStore } from "./auth-storage";
import { RangookApp, isRangookAppAvailable } from "./rangook-app";
import { createNativeServices } from "./services";

/** Starts the app layer. AuthProvider waits for it, so only first-screen work belongs here. */
export async function bootstrapNative(): Promise<void> {
    const info = await readAppInfo();
    setAppInfo(info);
    installPlatformServices(createNativeServices(info));

    // Before AuthProvider's first read: this decides logged-in vs login screen.
    setAuthValueStore(await createNativeAuthStore());

    setSentryAppContext(info);
    startNativeUpdates();
}

async function readAppInfo(): Promise<AppInfo> {
    const base = getAppInfo();
    const platform = Capacitor.getPlatform();

    // The native bundle opened in a browser (debugging): stay on web defaults.
    if (platform !== "android" && platform !== "ios") return base;

    const [binary, device] = await Promise.all([readBinary(), readDevice()]);

    // device_name at login (the User-Agent would say Chrome).
    const deviceName = [
        "App",
        device?.os,
        device?.model,
        [binary.channel, binary.native?.version].filter(Boolean).join(" "),
    ].filter(Boolean).join(" | ");

    return {
        ...base,
        platform,
        channel: binary.channel,
        native: binary.native,
        deviceName,
    };
}

async function readBinary(): Promise<{ channel: AppInfo["channel"]; native: NativeBinaryInfo | null }> {
    try {
        if (isRangookAppAvailable()) {
            const build = await RangookApp.getBuildInfo();
            return {
                channel: toChannel(build.channel),
                native: {
                    applicationId: build.applicationId,
                    version: build.versionName,
                    build: build.versionCode,
                },
            };
        }

        // No RangookApp plugin (iOS for now): the version is known, the channel is not.
        const app = await App.getInfo();
        return {
            channel: "unknown",
            native: {
                applicationId: app.id,
                version: app.version,
                build: Number.parseInt(app.build, 10) || 0,
            },
        };
    } catch (err) {
        console.warn("[platform] could not read build info:", err);
        return { channel: "unknown", native: null };
    }
}

async function readDevice(): Promise<{ os: string; model: string } | null> {
    try {
        const device = await Device.getInfo();
        const os = device.platform === "ios" ? "iOS" : "Android";
        return {
            os: `${os} ${device.osVersion}`,
            model: [device.manufacturer, device.model].filter(Boolean).join(" ") || "Unknown",
        };
    } catch {
        return null;
    }
}
