import { readable, type Readable } from 'svelte/store';

interface ReputationState {
	reputation: number;
	loading: boolean;
}

const reputationStores = new Map<string, Readable<ReputationState>>();

export function getReputationStore(pubkey: string): Readable<ReputationState> {
	if (reputationStores.has(pubkey)) {
		return reputationStores.get(pubkey)!;
	}

	const store = readable<ReputationState>({ reputation: 0, loading: true }, (set) => {
		let isSubscribed = true;

		async function getRep() {
			try {
				const reputation = await window.eve.getReputation(pubkey);
				if (isSubscribed) {
					set({ reputation, loading: false });
				}
			} catch (error) {
				console.error(`Failed to get reputation for ${pubkey}:`, error);
				if (isSubscribed) {
					set({ reputation: 0, loading: false }); // Or handle error state differently
				}
			}
		}

		getRep();

		const subscription = window.eve
			.subscribeToEvents({
				kinds: [7],
				'#p': [pubkey]
			})
			.subscribe(() => getRep());

		return () => {
			isSubscribed = false;
			subscription.unsubscribe();
			reputationStores.delete(pubkey);
		};
	});

	reputationStores.set(pubkey, store);
	return store;
}
