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

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

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

import { getIntl } from "@/i18n"

export default async function Layout(props: LayoutProps<"/[lang]/webview">) {
  const params = await props.params

  const { children } = props
  const intl = await getIntl()
  const [user, error] = await safeTry(getBasicProfile())

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

  const notValidSession =
    error instanceof TRPCError &&
    (error.code === "UNAUTHORIZED" || error.code === "FORBIDDEN")

  if (notValidSession) {
    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)
  }

  if (error instanceof TRPCError) {
    switch (error.code) {
      case "NOT_FOUND":
        return (
          <p>
            {intl.formatMessage({
              id: "webview.userNotFoundError",
              defaultMessage: "Error: User not found",
            })}
          </p>
        )
      default:
        logger.error("[webview:page] unexpected error code loading user", error)
        Sentry.captureException(error, {
          data: {
            errorCode: error.code,
            message: "[webview:page] unexpected error code loading user",
          },
        })

        return (
          <p>
            {intl.formatMessage({
              id: "webview.genericUserError",
              defaultMessage: "Unknown error occurred loading user",
            })}
          </p>
        )
    }
  }

  return <>{children}</>
}
