/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import { withIronSessionSsr } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import useUser from "@/hooks/useUser";
import PaymentDue from "./(status)/PaymentDue";
import { useRouter } from "next/router";
import { requestUser } from "@/utils/api";
import { mapBy, redirect, serialize } from "@/utils";
import { getEntities } from "@/utils/entities.be";
import { isAdmin } from "@/utils/users";
import { EntityWithRoles } from "@/interfaces/entity";
import { User } from "@/interfaces/user";

export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
	const user = await requestUser(req, res)
	if (!user) return redirect("/login")

	const entityIDs = mapBy(user.entities, 'id')
	const entities = await getEntities(isAdmin(user) ? undefined : entityIDs)

	return {
		props: serialize({ user, entities }),
	};
}, sessionOptions);

interface Props {
	user: User,
	entities: EntityWithRoles[]
}

export default function Home({ user, entities }: Props) {
	const router = useRouter();

	return (
		<>
			<Head>
				<title>EnCoach</title>
				<meta
					name="description"
					content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
				/>
				<meta name="viewport" content="width=device-width, initial-scale=1" />
				<link rel="icon" href="/favicon.ico" />
			</Head>
			<PaymentDue entities={entities} user={user} reload={router.reload} />
		</>
	);
}
