<script lang="ts">
	import { createCollection } from '@tanstack/svelte-db';
	import { queryCollectionOptions } from '@tanstack/query-db-collection';
	import { getRouter } from "$lib/getconnectrouter"
	import favicon from '$lib/assets/favicon.svg';
	import "../app.css"
  import { QueryClient, QueryClientProvider } from '@tanstack/svelte-query';
    import type { ExtractPayload, Todo } from '@<@var(context.project.name)>/rpc';
    import { browser } from '$app/environment';
	import { setTodoCollection } from '$lib/todocollectionscontext';

	let { children } = $props();
	const router = getRouter()
	const queryClient = new QueryClient({
		defaultOptions: {
			queries: {
				enabled: browser
			}
		},
	})
	const todosCollection = createCollection(
		queryCollectionOptions({
			queryKey: ["todos"],
			queryFn: async () => {
				const todos = await router.todos.listTodos({})
				return todos.todos as ExtractPayload<Todo>[];
			},
			queryClient,
			getKey: (item) => item.id ? item.id : crypto.randomUUID(),
			onInsert: async ({transaction}) => {
				Promise.all(transaction.mutations.map((m) => {
					router.todos.createTodo({ todo: m.modified })
				}))
			},
			onDelete: async ({transaction}) => {
				Promise.all(transaction.mutations.map((m) => {
					router.todos.deleteTodo({todo: m.modified})
				}))
			},
			onUpdate: async ({transaction}) => {
				Promise.all(transaction.mutations.map((m) => {
					router.todos.updateTodo({todo: m.modified})
				}))
			}
		})
	)
	setTodoCollection(todosCollection)
</script>


<QueryClientProvider client={queryClient}>
	{@render children()}
</QueryClientProvider>
