// src/lib/stores/businessInfo.svelte.ts
import type { BusinessSettings } from '$lib/types/settings';

let businessInfo = $state<BusinessSettings | null>(null);
let loadingPromise: Promise<BusinessSettings | null> | null = null;

/**
 * Fetches /api/business-info exactly once and caches the result.
 * Subsequent calls return the cached promise or resolved value.
 * Errors are handled gracefully — returns null.
 */
export async function ensureBusinessInfo(): Promise<BusinessSettings | null> {
	if (businessInfo !== null) return businessInfo;
	if (loadingPromise) return loadingPromise;

	loadingPromise = fetch('/api/business-info')
		.then((r) => (r.ok ? r.json() : null))
		.then((data) => {
			businessInfo = data as BusinessSettings | null;
			return businessInfo;
		})
		.catch(() => {
			businessInfo = null;
			return null;
		});

	return loadingPromise;
}

/**
 * Returns the current cached business info (reactive via $state).
 * Use in $derived or $effect to track changes.
 */
export function getBusinessInfo(): BusinessSettings | null {
	return businessInfo;
}
