---
import { createCaller } from "../../astro-typesafe-api-caller.js";
import { validateAccessTokenServer } from "#server/lib/validateAccessToken";
import DashboardModule from "#modules/Dashboard/DashboardModule.svelte";
import { API_ACCESS_TOKEN_COOKIE_NAME } from "#lib/constants";
import { prisma } from "#lib/server/prisma";
import DashboardLayout from "#layouts/DashboardLayout.astro";

const accessTokenValid = await validateAccessTokenServer(Astro);

if (!accessTokenValid) {
	return Astro.redirect("/auth/login")
}

const caller = createCaller(Astro);

const user = await caller.user.self.GET.fetch(undefined, {
	headers: {
		"Authorization": `Bearer ${Astro.cookies.get(API_ACCESS_TOKEN_COOKIE_NAME)?.value}`
	}
});

if (!user) {
	return Astro.redirect("/auth/login")
}

const objekte = await prisma.objekt.findMany({
	where: {
		benutzer: {
			uid: user.uid
		}
	},
	take: 10,
	include: {
		aufnahmen: {
			include: {
				bilder: true,
				unterlagen: true,
				bedarfsausweise_wohnen: true,
				verbrauchsausweise_gewerbe: true,
				verbrauchsausweise_wohnen: true
			}
		}
	}
})
---

<DashboardLayout title="Dashboard" {user}>
	<DashboardModule {user} {objekte} />
</DashboardLayout>