"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateModelContext = generateModelContext;
const generator_1 = require("@postxl/generator");
function generateModelContext({ model }) {
    const imports = generator_1.ImportGenerator
        //
        .from(model.table.allModelsHook.location)
        .addType(model.types)
        .addType(model.types.id);
    const resultMapTypeDefinition = `Map<${model.types.id.name}, ${model.types.name}>`;
    return `
import { useMemo } from 'react'

import { useQuery } from '@tanstack/react-query'

import { useTRPC } from '@lib/trpc'

${imports.generate()}

type ProviderHookType = {
	ready: boolean
	map: ${resultMapTypeDefinition}
	list: ${model.types.name}[]
}

/**
 * A React utility hook to access the model data in the generated forms.
 */
export const ${model.table.allModelsHook.name} = (): ProviderHookType => {
  const trpc = useTRPC()
  const dataQuery = useQuery(trpc.${model.trpcRoute.name}.${model.trpcRoute.getMap.name}.queryOptions())

	const value = useMemo<ProviderHookType>(() => {
		const data: ${resultMapTypeDefinition} = dataQuery.data ?? new ${resultMapTypeDefinition}()

		return {
			ready: dataQuery.isLoading === false,
			map: data,
			list: Array.from(data.values())
		}
	}, [dataQuery.isLoading, dataQuery.data])

	return value
}

/**
 * Returns a single instance of the model if the data is ready.
 */
export const ${model.table.modelHook.name} = (
	{ id }: { id?: ${model.types.id.name} | null }
): ${model.types.name} | null => {
	const { map, ready } = ${model.table.allModelsHook.name}()

	const value = useMemo(() => {
		if (!ready || !id) {
			return null
		}

		const val = map.get(id)
		if (!val) {
			return null
		}

		return val
	}, [map, ready, id])

	return value
}
`;
}
//# sourceMappingURL=model-context.generator.js.map