import type { GetServerSideProps } from "next";
import { AllegatiComp } from "~/components/area-riservata/allegati";
import { AreaRiservataLayoutUserView } from "~/components/Layout";
import type { NextPageWithLayout } from "~/pages/_app";
import type { UsersId } from "~/schemas/public/Users";
import { TrpcAuthedFetchingIstance } from "~/server/utils/ssgHelper";
import { zUserId } from "~/server/utils/zod_types";

type AllegatiProps = {
	userId: UsersId;
};

/**
 * Pagina di visualizzazione allegati per admin: /area-riservata/admin/user-view/allegati/[userId]
 */
const AllegatiUser: NextPageWithLayout<AllegatiProps> = ({
	userId,
}: AllegatiProps) => {
	return (
		<div className="grow px-1">
			<AllegatiComp isAdmin userId={userId} />
		</div>
	);
};
export default AllegatiUser;

export const getServerSideProps = (async (context) => {
	const userId = context.params?.userId;
	if (typeof userId !== "string") {
		return {
			notFound: true,
		};
	}

	const parsed = zUserId.safeParse(userId);

	if (!parsed.success) {
		return {
			notFound: true,
		};
	}
	const access_token = context.req.cookies.access_token;

	const helpers = await TrpcAuthedFetchingIstance({ access_token });
	if (helpers) {
		await helpers.trpc.storage.retrieveUserFileData.prefetch({
			userId: parsed.data,
		});
		return {
			props: {
				userId: parsed.data,
				trpcState: helpers.trpc.dehydrate(),
			},
		};
	}
	return {
		notFound: true,
	};
}) satisfies GetServerSideProps<AllegatiProps>;

AllegatiUser.getLayout = function getLayout(page) {
	return <AreaRiservataLayoutUserView>{page}</AreaRiservataLayoutUserView>;
};
