/**
 * Shared health store. Both the sidebar status chips and the dashboard
 * daemon panel subscribe to this single source so the server is not
 * polled twice for the same data.
 *
 * Poll cadence is 30 seconds — matching the previous layout-local
 * implementation. An out-of-band `refreshHealth()` call is exposed for
 * user-initiated "retry now" actions.
 */

import { writable, type Readable } from 'svelte/store';
import * as api from '$lib/api';
import { isAuthenticated } from '$lib/auth';
import type { DockerHealth, ProxyHealth } from '$lib/types';

export interface HealthSnapshot {
	docker: DockerHealth | null;
	proxy: ProxyHealth | null;
	/** true once the first poll (success or failure) has completed. */
	checked: boolean;
	/** ms epoch of the last successful or attempted poll. */
	lastUpdated: number;
}

const EMPTY: HealthSnapshot = {
	docker: null,
	proxy: null,
	checked: false,
	lastUpdated: 0
};

const store = writable<HealthSnapshot>(EMPTY);

export const health: Readable<HealthSnapshot> = { subscribe: store.subscribe };

let pollTimer: ReturnType<typeof setInterval> | null = null;
let inFlight = false;

async function refreshOnce(): Promise<void> {
	if (inFlight || !isAuthenticated()) return;
	inFlight = true;
	try {
		const h = await api.getHealth();
		store.set({
			docker: h.docker,
			proxy: h.proxy ?? null,
			checked: true,
			lastUpdated: Date.now()
		});
	} catch {
		store.update((prev) => ({
			docker: prev.docker ?? { connected: false },
			proxy: prev.proxy,
			checked: true,
			lastUpdated: Date.now()
		}));
	} finally {
		inFlight = false;
	}
}

export function startHealthPolling(intervalMs = 30_000): void {
	if (pollTimer) return;
	void refreshOnce();
	pollTimer = setInterval(() => void refreshOnce(), intervalMs);
}

export function stopHealthPolling(): void {
	if (pollTimer) {
		clearInterval(pollTimer);
		pollTimer = null;
	}
}

export function refreshHealth(): Promise<void> {
	return refreshOnce();
}
