import { MetaProvider, Title } from "@solidjs/meta";
import { Router } from "@solidjs/router";
import { FileRoutes } from "@solidjs/start/router";
import { Suspense } from "solid-js";
import { createCollection } from '@tanstack/solid-db'
import { queryCollectionOptions } from '@tanstack/query-db-collection'
import type { Todo, ExtractPayload } from '@<@var(context.project.name)>/rpc'
import { QueryClient, QueryClientProvider } from "@tanstack/solid-query"
import { getRouter } from "./lib/getRouter"
import "./app.css";
import { TodoCollectionProvider } from "./context/todocollection/provider";
const queryClient = new QueryClient({

})
const router = getRouter();
export default function App() {
  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 })
        }))
      }
    })
  )
  return (
    <Router
      root={props => (
        <MetaProvider>
          <QueryClientProvider client={queryClient} >
            <TodoCollectionProvider value={todosCollection}>
              <Suspense>{props.children}</Suspense>
            </TodoCollectionProvider>
          </QueryClientProvider>
        </MetaProvider>
      )}
    >
      <FileRoutes/>
    </Router>
  );
}
