// #region HealthStore [C:3] [TYPE Store] [SEMANTICS health, store, dashboard, summary, badge]
// @BRIEF Manage dashboard health summary state and failing counts for UI badges.
// @LAYER UI
// @RELATION DEPENDS_ON -> [ApiModule]
// @UX_STATE Loading -> Loading spinner, badges hidden
// @UX_STATE Ready -> Health summary displayed with pass/warn/fail counts
// @UX_STATE Error -> Error state with retry option
// @RATIONALE Migrated from Svelte 4 writable/derived stores to Svelte 5 $state runes.
//            Keeps .subscribe() for backward compat with fromStore() in Sidebar.svelte.
//            Explicit _notify() instead of $effect to avoid effect_orphan error in test contexts.

import { api } from '../api';

interface HealthState {
	items: unknown[];
	pass_count: number;
	warn_count: number;
	fail_count: number;
	unknown_count: number;
	loading: boolean;
	lastUpdated: Date | null;
}

// Module-level state atoms
let _items = $state<unknown[]>([]);
let _pass_count = $state(0);
let _warn_count = $state(0);
let _fail_count = $state(0);
let _unknown_count = $state(0);
let _loading = $state(false);
let _lastUpdated = $state<Date | null>(null);

// Subscriber sets for backward compat
const _healthSubs = new Set<() => void>();
const _failingCountSubs = new Set<(v: number) => void>();

function _notifyHealth(): void {
	_healthSubs.forEach(fn => fn());
}

function _notifyFailingCount(): void {
	_failingCountSubs.forEach(fn => fn(_fail_count));
}

function _setStateFromSummary(summary: Partial<HealthState>): void {
	_items = summary.items || [];
	_pass_count = summary.pass_count || 0;
	_warn_count = summary.warn_count || 0;
	_fail_count = summary.fail_count || 0;
	_unknown_count = summary.unknown_count || 0;
	_loading = summary.loading ?? false;
	if (summary.lastUpdated) _lastUpdated = summary.lastUpdated;
}

// Inflight request dedup
let inflightRefresh: Promise<unknown> | null = null;
let inflightEnvironmentId: string | null = null;
let _isDisabled = false;

async function refresh(environmentId: string | null = null): Promise<unknown> {
	if (_isDisabled) return null;

	const normalizedEnvironmentId = environmentId || null;
	if (inflightRefresh && inflightEnvironmentId === normalizedEnvironmentId) {
		return inflightRefresh;
	}

	_loading = true;
	_notifyHealth();
	inflightEnvironmentId = normalizedEnvironmentId;
	inflightRefresh = (async () => {
		try {
			const summary = await api.getHealthSummary<HealthState>(environmentId ?? undefined);
			_setStateFromSummary(summary);
			_lastUpdated = new Date();
			_notifyHealth();
			_notifyFailingCount();
			return summary;
		} catch (error: unknown) {
			const msg = (error as Error)?.message || String(error);
			if (msg.includes('Health monitor feature is disabled') || msg.includes('404')) {
				console.warn('[HealthStore] Health monitor feature is disabled — stopping polling');
				_isDisabled = true;
			}
			console.error('[HealthStore] Failed to fetch health summary:', error);
			_loading = false;
			_notifyHealth();
			return null;
		} finally {
			inflightRefresh = null;
			inflightEnvironmentId = null;
		}
	})();
	return inflightRefresh;
}

export const healthStore = {
	get items() { return _items; },
	get pass_count() { return _pass_count; },
	get warn_count() { return _warn_count; },
	get fail_count() { return _fail_count; },
	get unknown_count() { return _unknown_count; },
	get loading() { return _loading; },
	get lastUpdated() { return _lastUpdated; },
	subscribe(fn: () => void) {
		fn();
		_healthSubs.add(fn);
		return () => _healthSubs.delete(fn);
	},
	refresh,
};

export const failingCount = {
	get current() { return _fail_count; },
	subscribe(fn: (v: number) => void) {
		fn(_fail_count);
		_failingCountSubs.add(fn);
		return () => _failingCountSubs.delete(fn);
	},
};
// #endregion HealthStore
