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

interface Data {
	users: Record<string, UserWithTodos>
	todos: Record<string, Todo>
	unassignedTodos: Todo[]
	lastUserIdUpdated: { value: string; versionstamp: string }
	lastTodoIdUpdated: { value: string; versionstamp: string }
}

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 todos = Object.fromEntries(
			(await db.todos.findMany({})).map(
				(t) => [t.id, t],
			),
		)
		const unassignedTodos = await db.todos.findMany({
			where: { assigneeUserId: null },
		})
		const [lastUserIdUpdated, lastTodoIdUpdated] = await kv.getMany([[
			'last_user_updated',
		], ['last_todo_updated']], { consistency: 'eventual' })
		console.log({ lastTodoIdUpdated, lastUserIdUpdated })
		return ctx.render({
			users,
			todos,
			unassignedTodos,
			lastUserIdUpdated,
			lastTodoIdUpdated,
		})
	},
}

export default function Home({ data }: PageProps<Data>) {
	console.log('Home rendered')
	return <Dashboard {...data} />
}
