import {
	createFileRoute,
	Link,
	Outlet,
	redirect,
} from "@tanstack/react-router";
import { checkUserAccess } from "@/lib/authClient";

export const Route = createFileRoute("/_app/_adminLayout/admin/_system")({
	component: RouteComponent,
	beforeLoad: async () => {
		const auth = await checkUserAccess({
			allowedRoles: ["systemAdmin", "admin"],
			moduleName: "system", // optional
		});

		if (!auth) {
			throw redirect({
				to: "/login",
				search: {
					// Use the current location to power a redirect after login
					// (Do not use `router.state.resolvedLocation` as it can
					// potentially lag behind the actual current location)
					redirect: location.pathname + location.search,
				},
			});
		}
	},
});

function RouteComponent() {
	return (
		<div>
			<nav className="flex justify-center gap-3">
				<Link
					to="/admin/settings"
					className="[&.active]:font-bold [&.active]:underline"
					activeOptions={{
						exact: true,
					}}
				>
					Settings
				</Link>
				<Link
					to="/admin/modules"
					className="[&.active]:font-bold [&.active]:underline"
					activeOptions={{
						exact: true,
					}}
				>
					Modules
				</Link>
			</nav>
			<Outlet />
		</div>
	);
}
