import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';
import { coursesQueryOptions } from '../api/queries';
import { CoursesTable } from './course-tables';

function normalizeSingleSelectParam(value?: string | null) {
  const normalized = value
    ?.split(/[.,]/)
    .map((item) => item.trim())
    .find(Boolean);

  return normalized && normalized !== 'all' ? normalized : null;
}

export default async function CourseListingPage() {
  const page = searchParamsCache.get('page');
  const search = searchParamsCache.get('name');
  const pageLimit = searchParamsCache.get('perPage');
  const category = normalizeSingleSelectParam(searchParamsCache.get('category'));
  const status = normalizeSingleSelectParam(searchParamsCache.get('status'));
  const sort = searchParamsCache.get('sort');

  const filters = {
    page,
    limit: pageLimit,
    ...(search && { search }),
    ...(category && { category }),
    ...(status && { status }),
    ...(sort && { sort })
  };

  const queryClient = getQueryClient();
  await queryClient.fetchQuery(coursesQueryOptions(filters));

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <CoursesTable />
    </HydrationBoundary>
  );
}
