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

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

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>) {
	return <Dashboard {...data} />
}
