import { GetUnreadMessageCountStore, GetUnreadNotificationCountStore } from '$houdini';

const isBrowser = typeof window !== 'undefined';
const POLL_INTERVAL = 30000; // 30 seconds

interface UnreadCounts {
	messages: number;
	notifications: number;
}

function createUnreadCountsStore() {
	let counts = $state<UnreadCounts>({ messages: 0, notifications: 0 });
	let pollIntervalId: ReturnType<typeof setInterval> | null = null;
	let isPolling = $state(false);

	const messageCountStore = new GetUnreadMessageCountStore();
	const notificationCountStore = new GetUnreadNotificationCountStore();

	async function fetchCounts(): Promise<void> {
		if (!isBrowser) return;

		try {
			// Fetch both counts in parallel
			const [messageResult, notificationResult] = await Promise.all([
				messageCountStore.fetch(),
				notificationCountStore.fetch()
			]);

			counts = {
				messages: messageResult.data?.unreadMessageCount ?? 0,
				notifications: notificationResult.data?.myUnreadNotificationCount ?? 0
			};
		} catch (error) {
			console.warn('Failed to fetch unread counts:', error);
		}
	}

	function startPolling(): void {
		if (!isBrowser || isPolling) return;

		isPolling = true;

		// Initial fetch
		fetchCounts();

		// Set up polling interval
		pollIntervalId = setInterval(() => {
			fetchCounts();
		}, POLL_INTERVAL);
	}

	function stopPolling(): void {
		if (pollIntervalId) {
			clearInterval(pollIntervalId);
			pollIntervalId = null;
		}
		isPolling = false;
	}

	function resetCounts(): void {
		counts = { messages: 0, notifications: 0 };
	}

	function decrementMessages(by: number = 1): void {
		counts = {
			...counts,
			messages: Math.max(0, counts.messages - by)
		};
	}

	function decrementNotifications(by: number = 1): void {
		counts = {
			...counts,
			notifications: Math.max(0, counts.notifications - by)
		};
	}

	function incrementMessages(by: number = 1): void {
		counts = {
			...counts,
			messages: counts.messages + by
		};
	}

	function incrementNotifications(by: number = 1): void {
		counts = {
			...counts,
			notifications: counts.notifications + by
		};
	}

	return {
		get counts() {
			return counts;
		},
		get messageCount() {
			return counts.messages;
		},
		get notificationCount() {
			return counts.notifications;
		},
		get isPolling() {
			return isPolling;
		},
		startPolling,
		stopPolling,
		fetchCounts,
		resetCounts,
		decrementMessages,
		decrementNotifications,
		incrementMessages,
		incrementNotifications
	};
}

export const unreadCounts = createUnreadCountsStore();
