import * as Sentry from "@sentry/nextjs"
import { headers } from "next/headers"
import { redirect } from "next/navigation"

import { logger } from "@scandic-hotels/common/logger"

import { getProfile } from "@/lib/trpc/memoizedRequests"

import { getIntl } from "@/i18n"

import type { LangParams, LayoutArgs } from "@/types/params"

export default async function Layout(
  props: React.PropsWithChildren<LayoutArgs<LangParams>>
) {
  const params = await props.params

  const { children } = props
  const intl = await getIntl()
  const user = await getProfile()

  if (!user) {
    logger.debug(`[webview:page] unable to load user`)
    return (
      <p>
        {intl.formatMessage({
          id: "webview.missingUserError",
          defaultMessage: "Error: No user could be loaded",
        })}
      </p>
    )
  }

  if ("error" in user) {
    switch (user.cause) {
      case "unauthorized": // fall through
      case "forbidden": // fall through
      case "token_expired":
        const headersList = await headers()
        const returnURL = `/${params.lang}/webview${headersList.get("x-pathname")!}`
        const redirectURL = `/${params.lang}/webview/refresh?returnUrl=${encodeURIComponent(returnURL)}`
        logger.debug(
          `[webview:page] user error, redirecting to: ${redirectURL}`
        )
        redirect(redirectURL)
      case "notfound":
        return (
          <p>
            {intl.formatMessage({
              id: "webview.userNotFoundError",
              defaultMessage: "Error: user not found",
            })}
          </p>
        )
      case "unknown":
        return (
          <p>
            {intl.formatMessage({
              id: "webview.genericUserError",
              defaultMessage: "Unknown error occurred loading user",
            })}
          </p>
        )
      default:
        const u: never = user
        logger.error("[webview:page] unhandled user loading error", u)
        Sentry.captureMessage("[webview:page] unhandled user loading error", u)
    }
  }

  return <>{children}</>
}
