import { headers } from 'next/headers'
import { redirect } from 'next/navigation'
import { resolveServerAppUrl } from '@/lib/appUrls'

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

function buildSearch(params: SearchParams): string {
  const nextParams = new URLSearchParams()

  for (const [key, value] of Object.entries(params)) {
    if (typeof value === 'string') {
      nextParams.set(key, value)
      continue
    }

    if (Array.isArray(value)) {
      for (const entry of value) nextParams.append(key, entry)
    }
  }

  const search = nextParams.toString()
  return search ? `?${search}` : ''
}

export default async function RenterSignInPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}) {
  const requestHeaders = await headers()
  const dashboardUrl = resolveServerAppUrl(
    process.env.NEXT_PUBLIC_HOMEPAGE_URL ?? 'http://localhost:3000',
    requestHeaders.get('host'),
    requestHeaders.get('x-forwarded-proto'),
  )
  const params = await searchParams

  redirect(`${dashboardUrl}/sign-in${buildSearch(params)}`)
}
