/* 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, getEntitiesWithRoles } from "@/utils/entities.be";
import { isAdmin } from "@/utils/users";
import { EntityWithRoles } from "@/interfaces/entity";
import { User } from "@/interfaces/user";
import client from "@/lib/mongodb";
import { Discount, Package } from "@/interfaces/paypal";

const db = client.db(process.env.MONGODB_DB);

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 domain = user.email.split("@").pop()
	const [entities, discounts, packages] = await Promise.all([
		getEntitiesWithRoles(isAdmin(user) ? undefined : entityIDs),
		db.collection<Discount>("discounts").find({ domain }).toArray(),
		db.collection<Package>("packages").find().toArray(),
	])

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

interface Props {
	user: User,
	entities: EntityWithRoles[]
	discounts: Discount[]
	packages: Package[]
}

export default function Home(props: 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 {...props} reload={router.reload} />
		</>
	);
}
