import type { AppRegistryMap, AppRegistryEntry } from '../../components/Workspace';
import { useGlobal } from 'hooks/useGlobal';

export type AppRegistryMeta = { key: string } & AppRegistryEntry;

export function useAppRegistry(initialApps: AppRegistryMeta[] = []) {
  const [registry, setRegistry] = useGlobal<AppRegistryMap>('APP_REGISTRY', () => metasToRegistry(initialApps));

  const registerApp = (key: string, entry: AppRegistryEntry) => {
    setRegistry((prev) => ({ ...prev, [key]: entry }));
  };

  return { registry, registerApp };
}

export type UseAppRegistryType = ReturnType<typeof useAppRegistry>;

const metasToRegistry = (metas: AppRegistryMeta[]): AppRegistryMap =>
  Object.fromEntries(metas.map(({ key, ...entry }) => [key, entry]));
