import axios from "axios";
import Constants from "expo-constants";
import { useAppStore } from "../hooks/useAppStore";
import { useServerStore } from "../hooks/useServerCheck";
import { downloadLatestApk } from "./lastestVersion";

export type ServerVersionInfo = {
	packageName: string;
	versionName: string;
	versionCode: number;
	minSupportedVersionCode: number;
	fileName: string;
};

export type StartupStatus =
	| { state: "checking" }
	| { state: "needs-config" }
	| { state: "offline" }
	| { state: "blocked"; reason: string; server: ServerVersionInfo }
	| { state: "warning"; message: string; server: ServerVersionInfo }
	| { state: "ready"; server: ServerVersionInfo | null };

export function evaluateVersion(
	appBuildCode: number,
	server: ServerVersionInfo,
): StartupStatus {
	if (appBuildCode < server.minSupportedVersionCode) {
		return {
			state: "blocked",
			reason: "This scanner app is too old and must be updated before use.",
			server,
		};
	}

	if (appBuildCode !== server.versionCode) {
		return {
			state: "warning",
			message: `A newer version is available. Installed build: ${appBuildCode}, latest build: ${server.versionCode}.`,
			server,
		};
	}

	return {
		state: "ready",
		server,
	};
}

export const versionCheck = async () => {
	const { setServerVersion } = useServerStore.getState();
	const { serverPort, serverIp } = useAppStore.getState();

	const port = parseInt(serverPort || "0", 10) >= 50000 ? "3000" : serverPort;

	try {
		const res = await axios.get(
			`http://${serverIp}:${port}/lst/api/mobile/version`,
			{ timeout: 5000 },
		);

		if (res.status === 200) {
			setServerVersion(res.data);
		}

		const build = Constants.expoConfig?.android?.versionCode ?? 1;

		if (build < res.data.versionCode) {
			//await downloadLatestApk(serverIp, port);
		}
	} catch (error) {
		console.log("Version check error:", error);
	}
};
