import { Handlers, PageProps } from '$fresh/server.ts'
import { db, kv, schema, Todo, UserWithTodos } from '@homeman/models.ts'
import Dashboard from '@homeman/islands/Dashboard.tsx'
import { useSignal } from '@preact/signals'
import { useEffect } from 'preact/hooks'

interface Data {
	users: Record<string, UserWithTodos>
	unassignedTodos: Todo[]
}

const allTableNames = Object.keys(schema).map((s) => [s])
async function watcher() {
	console.log('watching:', allTableNames)
	for await (const entry of kv.watch(allTableNames)) {
		console.log('entry:', entry)
	}
}
watcher()

export const handler: Handlers = {
	async GET(_req, ctx) {
		const users = Object.fromEntries(
			(await db.users.findMany({ include: { assignedTodos: true } })).map(
				(u) => [u.id, u],
			),
		)
		const unassignedTodos = await db.todos.findMany({
			where: { assigneeUserId: null },
		})
		return ctx.render({ users, unassignedTodos })
	},
}

export default function Home({ data }: PageProps<Data>) {
	const rdata = useSignal(data)
	useEffect(() => {
		async function watcher() {
			console.log('watcher watching...')
			for await (const entry of kv.watch(allTableNames)) {
				console.log('entry:', entry)
			}
		}
		watcher().catch(console.error)
	}, [rdata])
	console.log('Home rendered')
	return <Dashboard {...rdata.value} />
}
