import { redirect } from "next/navigation"

import { resolveRoleFromServerContext } from "@/lib/access-server"
import { hasOwnerUser } from "@/lib/auth/server"

import { LoginForm } from "./login-form"

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 LoginPage({ 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)}`)
  }

  return <LoginForm mode="signin" />
}
