// app/auth/sign-in/page.tsx
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import SignIn from "./sign-in";

export default async function SignInPage(
    props: { searchParams: Promise<Record<string, string | string[] | undefined>> }
) {
    const sp = await props.searchParams;

    const nextParam = Array.isArray(sp.next) ? sp.next[0] : sp.next;
    const nextPath = nextParam && nextParam.startsWith("/") ? nextParam : "/portal";

    const reauthParam = Array.isArray(sp.reauth) ? sp.reauth[0] : sp.reauth;
    const forceParam  = Array.isArray(sp.force)  ? sp.force[0]  : sp.force;
    const reauth = reauthParam === "1" || forceParam === "1";

    // If reauth is requested, always render the form (no redirect).
    if (!reauth) {
        const at = (await cookies()).get("ma_at")?.value;
        if (at) redirect("/portal");
    }

    return <SignIn nextPath={nextPath} reauth={reauth} />;
}
