import { writable, get } from 'svelte/store';
import type { InstanceStatusPayload, DeployStatusPayload } from '$lib/sse';

/**
 * Global store for real-time instance status updates received via SSE.
 *
 * Components can subscribe to this store to reactively update when
 * instance statuses change without polling.
 */

interface InstanceStatusState {
	/** Map of instance ID to latest status. */
	statuses: Record<string, string>;
	/** Timestamp of last update, useful for triggering reactive refreshes. */
	lastUpdate: number;
	/** Latest deploy status events, keyed by deploy ID. */
	deployStatuses: Record<string, DeployStatusPayload>;
}

function createInstanceStatusStore() {
	const { subscribe, set, update: storeUpdate } = writable<InstanceStatusState>({
		statuses: {},
		lastUpdate: 0,
		deployStatuses: {}
	});

	return {
		subscribe,

		/** Update an instance's status from an SSE event. */
		update(payload: InstanceStatusPayload) {
			storeUpdate((state) => ({
				...state,
				statuses: {
					...state.statuses,
					[payload.instance_id]: payload.status
				},
				lastUpdate: Date.now()
			}));
		},

		/** Record a deploy status change from an SSE event. */
		notifyDeploy(payload: DeployStatusPayload) {
			storeUpdate((state) => ({
				...state,
				deployStatuses: {
					...state.deployStatuses,
					[payload.deploy_id]: payload
				},
				lastUpdate: Date.now()
			}));
		},

		/** Get the current status of an instance, or undefined if not tracked. */
		getStatus(instanceId: string): string | undefined {
			return get({ subscribe }).statuses[instanceId];
		},

		/** Reset the store (e.g., on disconnect). */
		reset() {
			set({
				statuses: {},
				lastUpdate: 0,
				deployStatuses: {}
			});
		}
	};
}

export const instanceStatusStore = createInstanceStatusStore();
