import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';
import { trainingRecordsQueryOptions } from '../api/queries';
import { TrainingRecordsTable } from './training-record-tables';

export default async function TrainingRecordListingPage() {
  const page = searchParamsCache.get('page');
  const search = searchParamsCache.get('user_name') ?? searchParamsCache.get('name');
  const pageLimit = searchParamsCache.get('perPage');
  const statuses = searchParamsCache.get('approval_status') ?? searchParamsCache.get('status');
  const types = searchParamsCache.get('training_type') ?? searchParamsCache.get('type');
  const sort = searchParamsCache.get('sort');

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

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

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