import { getContext } from 'svelte';
import { createOptimisticCount, type OptimisticCount } from '$lib/optimistic.svelte';
import type { ProfileCounts } from './types';

export type ProfileCountName = keyof ProfileCounts;

export interface ProfileCountsContext {
	readonly did: string;
	readonly value: ProfileCounts;
	adjust(subjectDid: string, name: ProfileCountName, delta: 1 | -1): void;
}

export const PROFILE_COUNTS_KEY = Symbol('profile-counts');

export const createProfileCounts = (
	did: () => string,
	loaded: () => ProfileCounts
): ProfileCountsContext => {
	const counter = (name: ProfileCountName): OptimisticCount =>
		createOptimisticCount({ key: did, loaded: () => loaded()[name] });

	const counts = {
		repos: counter('repos'),
		stars: counter('stars'),
		strings: counter('strings'),
		followers: counter('followers'),
		following: counter('following'),
		vouches: counter('vouches')
	};

	return {
		get did() {
			return did();
		},
		get value() {
			return {
				repos: counts.repos.value,
				stars: counts.stars.value,
				strings: counts.strings.value,
				followers: counts.followers.value,
				following: counts.following.value,
				vouches: counts.vouches.value
			};
		},
		adjust(subjectDid, name, delta) {
			if (subjectDid !== did()) return;
			counts[name].adjust(delta);
		}
	};
};

export const getProfileCounts = (): ProfileCountsContext | null =>
	getContext<ProfileCountsContext | null>(PROFILE_COUNTS_KEY);
