import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';
import { onlineLessonsQueryOptions } from '../api/queries';
import type { OnlineLessonCategory, OnlineLessonStatus } from '../api/types';
import OnlineLessonsPage from './online-lessons-page';

export default async function OnlineLessonsListingPage({
  currentUserId,
  permissions,
  canManageOnlineLessons = false
}: {
  currentUserId: string;
  permissions: readonly string[];
  canManageOnlineLessons?: boolean;
}) {
  const page = searchParamsCache.get('page');
  const perPage = searchParamsCache.get('perPage');
  const search = searchParamsCache.get('search');
  const category = searchParamsCache.get('category');
  const status = searchParamsCache.get('status');

  const filters = {
    page,
    limit: perPage,
    ...(search && { search }),
    ...(category ? { category: category as OnlineLessonCategory } : {}),
    ...(canManageOnlineLessons && status
      ? { status: status as OnlineLessonStatus }
      : {})
  };

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

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <OnlineLessonsPage
        currentUserId={currentUserId}
        permissions={permissions}
        canManageOnlineLessons={canManageOnlineLessons}
      />
    </HydrationBoundary>
  );
}
