import { getCategoryData } from '@akinon/next/data/server';
import { withSegmentDefaults } from '@akinon/next/hocs/server';
import { ResolvedPageProps } from '@akinon/next/types';
import CategoryLayout from '@theme/views/category/layout';
import { buildListingPageContext } from '@theme/utils/theme-page-context';
import { notFound } from 'next/navigation';

async function Page({ params, searchParams }: ResolvedPageProps<{ pk: number }>) {
  try {
    const { data, breadcrumbData } = await getCategoryData({
      pk: params.pk,
      searchParams
    });

    return (
      <>
        <CategoryLayout
          data={data}
          breadcrumbData={breadcrumbData}
          pageContext={buildListingPageContext({
            data,
            breadcrumbData,
            pageType: 'category',
            path: data.category?.absolute_url
          })}
        />
      </>
    );
  } catch (error: unknown) {
    if ((error as Error & { status?: number })?.status === 404) {
      notFound();
    }
    throw error;
  }
}

export default withSegmentDefaults(Page, { segmentType: 'page' });
