import React from 'react'
import { Merchant } from '@/lib/types/merchant'
import dynamic from 'next/dynamic'
import { notFound } from 'next/navigation'

const ClientWrapper = dynamic(() =>
  import('@/components/pages/ClientWrapper').then((mod) => mod.ClientWrapper),
)

// Server component function to fetch merchant data
async function getMerchant(username: string) {
  const res = await fetch(`${process.env.API_URL}/merchants/${username}`, {
    cache: 'no-store',
  })

  if (!res.ok) {
    notFound() // Redirect to 404 page if the response is not successful
  }

  return res.json()
}

export default async function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode
  params: Promise<{ username: string }>
}) {
  const { username } = await params
  const { data: merchant }: { data: Merchant } = await getMerchant(username)

  return <ClientWrapper merchant={merchant}>{children}</ClientWrapper>
}
