import { ElNotification } from 'element-plus';
import tool from '@/utils/tool';

const VERSION_KEY = 'APP_VERSION';
const VERSION_URL = '/version.json';
const POLL_INTERVAL = 5 * 60 * 1000; // 5分钟

let pollingTimer = null;

async function getServerVersion() {
	try {
		const res = await fetch(VERSION_URL, { cache: 'no-cache' });
		if (!res.ok) return null;
		const data = await res.json();
		return data.version;
	} catch (err) {
		console.warn('[VersionCheck] Failed to fetch version:', err);
		return null;
	}
}

export async function checkVersion() {
	const serverVersion = await getServerVersion();
	if (!serverVersion) return false;

	const localVersion = tool.data.get(VERSION_KEY);

	if (localVersion && localVersion !== serverVersion) {
		console.log('[VersionCheck] New version detected:', serverVersion);
		tool.data.set(VERSION_KEY, serverVersion);
		return true;
	}

	if (!localVersion) {
		tool.data.set(VERSION_KEY, serverVersion);
	}

	return false;
}

export function startPolling(interval = POLL_INTERVAL) {
	stopPolling();
	pollingTimer = setInterval(async () => {
		const hasUpdate = await checkVersion();
		if (hasUpdate) {
			stopPolling();
			ElNotification.info({
				title: '系统更新',
				message: '检测到新版本，正在刷新...',
				duration: 2000,
			});
			setTimeout(() => {
				window.location.reload();
			}, 2000);
		}
	}, interval);
}

export function stopPolling() {
	if (pollingTimer) {
		clearInterval(pollingTimer);
		pollingTimer = null;
	}
}
