"use server";
import { cookies } from "next/headers";

import CLoginForm from "@/components/client/admin/CLoginForm";
import ClientAuthHandler from "@/components/client/admin/CAuthHandler";

import { serverValidateSessionCookie } from "@/app/lib/actions/actions";
import { ReactNode } from "react";
import { AuthContextProviderProps } from "@/providers";

interface Props {
	children?: ReactNode;
	params?: any;
	requiredRole?: number;
} // We interfacing lads

export default async function AuthHandler(props: Props) {
	const protoKoek = await cookies().get("auth")?.value;
	const koek = decodeURIComponent(protoKoek ? protoKoek : "");
	// console.log("koekje:" + koek)
	let p: AuthContextProviderProps = {};
	if (koek) {
		const kd = JSON.parse(koek);
		if (kd.id && kd.token && kd.user_id) {
			p = {
				auth: {
					id: kd.id,
					token: kd.token,
					user_id: kd.user_id,
				},
			};
		}
	}

	return (
		<div className="flex flex-row w-[100%] h-[100%]">
			{!(koek && (await serverValidateSessionCookie(koek))) ? (
				<CLoginForm>{}</CLoginForm>
			) : (
				<ClientAuthHandler authProps={p}>
					{props.children}
				</ClientAuthHandler>
			)}
		</div>
	);
}
