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

export interface EveEvent {
	id?: string;
	pubkey: string;
	created_at: number;
	kind: number;
	tags: string[][];
	content: string;
	sig?: string;
}

interface EventStoreState {
	event: EveEvent | null;
	reputationGiven: boolean;
	isOwnEvent: boolean;
	loading: boolean;
}

const eventStores = new Map<string, Readable<EventStoreState>>();

export function getEventStore(eventId: string): Readable<EventStoreState> {
	if (eventStores.has(eventId)) {
		return eventStores.get(eventId)!;
	}

	const store = readable<EventStoreState>(
		{
			event: null,
			reputationGiven: false,
			isOwnEvent: false,
			loading: true
		},
		(set) => {
			let pubkey: string;
			let subscription: { unsubscribe: () => void } | undefined;

			async function load() {
				try {
					pubkey = await window.eve.getPublicKey();
					const event = await window.eve.getSingleEventById(eventId);

					if (!event) {
						set({ event: null, isOwnEvent: false, reputationGiven: false, loading: false });
						return;
					}

					const isOwnEvent = event.pubkey === pubkey;
					if (isOwnEvent) {
						set({ event, isOwnEvent: true, reputationGiven: false, loading: false });
						return;
					}

					const repEvents = await window.eve.getAllEventsWithFilter({
						kinds: [7],
						authors: [pubkey],
						'#e': [eventId]
					});

					const reputationGiven = repEvents.some((e) => e.content === '+' || e.content === '-');
					set({ event, isOwnEvent: false, reputationGiven, loading: false });

					if (!reputationGiven) {
						subscription = window.eve
							.subscribeToEvents({
								kinds: [7],
								authors: [pubkey],
								'#e': [eventId]
							})
							.subscribe(() => {
								set({ event, isOwnEvent: false, reputationGiven: true, loading: false });
								if (subscription) {
									subscription.unsubscribe();
									subscription = undefined;
								}
							});
					}
				} catch (e) {
					console.error(`Error loading event ${eventId}`, e);
					set({ event: null, isOwnEvent: false, reputationGiven: false, loading: false });
				}
			}
			load();

			return () => {
				if (subscription) {
					subscription.unsubscribe();
				}
				eventStores.delete(eventId);
			};
		}
	);

	eventStores.set(eventId, store);
	return store;
}
