/**
 * Global provider filter — persisted to localStorage.
 *
 * When set, pages should filter entities to show only those
 * belonging to the selected provider. null = show all.
 */

import { providersCache } from './caches.svelte';

const STORAGE_KEY = 'global_provider_id';

let _providerId = $state<number | null>(null);
let _initialized = $state(false);

function loadFromStorage(): void {
	if (typeof localStorage === 'undefined') return;
	const stored = localStorage.getItem(STORAGE_KEY);
	if (stored) {
		const parsed = parseInt(stored, 10);
		_providerId = isNaN(parsed) ? null : parsed;
	}
	_initialized = true;
}

// Load on module init
loadFromStorage();

export const globalProviderFilter = {
	/**
	 * Pure getter — returns whatever was last stored, never mutates. Stale-ID
	 * reconciliation against `providersCache` is the responsibility of a
	 * one-time `$effect` in `+layout.svelte` (see `reconcileStaleProviderId`),
	 * because writing during read inside a `$state`-derived getter triggers
	 * Svelte 5's `state_unsafe_mutation` warning.
	 */
	get id() { return _providerId; },
	get initialized() { return _initialized; },

	set(id: number | null) {
		_providerId = id;
		if (typeof localStorage !== 'undefined') {
			if (id != null) {
				localStorage.setItem(STORAGE_KEY, String(id));
			} else {
				localStorage.removeItem(STORAGE_KEY);
			}
		}
	},

	clear() {
		this.set(null);
	},

	/**
	 * Drop the stored provider ID if it no longer matches any item in the
	 * providers cache. Safe to call from a `$effect` after the cache has been
	 * fetched. Returns true when reconciliation actually changed state, so the
	 * caller can short-circuit follow-up work.
	 */
	reconcileWithCache(): boolean {
		if (_providerId != null && providersCache.items.length > 0 &&
			!providersCache.items.some(p => p.id === _providerId)) {
			this.clear();
			return true;
		}
		return false;
	},

	/** The currently selected provider object (reactive). */
	get provider() {
		const id = _providerId;
		if (id == null) return null;
		return providersCache.items.find(p => p.id === id) ?? null;
	},

	/** The provider type string, or null. */
	get providerType() {
		return this.provider?.type ?? null;
	},
};
