import type { ShTangledRepo } from "@atcute/tangled";
import { useParams } from "@solidjs/router";
import {
	createContext,
	createResource,
	type ParentComponent,
	type Resource,
	useContext,
} from "solid-js";
import { getUserRepo } from "../../util/get_repo";
import { figureOutDid } from "../../util/handle";
import type { DID } from "../../util/types";
import { getRepoForks, getRepoStars } from "./main.data";

const RepoContext = createContext<{
	did: () => DID | undefined;
	repoInfo: Resource<{
		repo: ShTangledRepo.Main & { rkey: string };
		stars: number;
		forks: number;
	}>;
}>();

export const RepoProvider: ParentComponent = (props) => {
	const params = useParams();
	const [did] = createResource(() => params.user, figureOutDid);

	const [repoInfo] = createResource(
		() => {
			const d = did();
			const r = params.repo;
			return d && r ? ([d, r] as const) : undefined;
		},
		async ([did, repo]) => {
			return {
				repo: await getUserRepo(did, repo),
				stars: await getRepoStars(did, repo),
				forks: await getRepoForks(did, repo),
			};
		},
	);

	return (
		<RepoContext.Provider value={{ did, repoInfo }}>
			{props.children}
		</RepoContext.Provider>
	);
};

export function useDid() {
	const ctx = useContext(RepoContext);
	if (!ctx) throw new Error("useDid must be used within RepoProvider");
	return ctx.did;
}

export function useRepoInfo() {
	const ctx = useContext(RepoContext);
	if (!ctx) throw new Error("useDid must be used within RepoProvider");
	return ctx.repoInfo;
}
