import { redirect } from "next/navigation"
import { LoginForm } from "@/app/login/login-form"
import { resolveRoleFromServerContext } from "@/lib/access-server"
import { hasOwnerUser, isSelfRegistrationEnabled } from "@/lib/auth/server"

export const dynamic = "force-dynamic"

type SearchParams = Promise<Record<string, string | string[] | undefined>>

function getSingleValue(input: string | string[] | undefined): string | undefined {
  if (Array.isArray(input)) {
    return input[0]
  }

  return input
}

export default async function RegisterPage({ searchParams }: { searchParams: SearchParams }) {
  const params = await searchParams
  const nextPath = getSingleValue(params.next) ?? "/"
  const role = await resolveRoleFromServerContext()

  if (role) {
    redirect("/")
  }

  const hasOwner = await hasOwnerUser()

  if (!hasOwner) {
    redirect(`/welcome?next=${encodeURIComponent(nextPath)}`)
  }

  const enabled = await isSelfRegistrationEnabled()

  if (!enabled) {
    return <LoginForm mode="signup-disabled" />
  }

  return <LoginForm mode="signup-user" />
}
