import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';
import { auditLogsQueryOptions } from '../api/queries';
import { AuditLogTable } from './audit-log-table';

export default async function AuditLogListingPage() {
  const page = searchParamsCache.get('page');
  const pageLimit = searchParamsCache.get('perPage');
  const search = searchParamsCache.get('search');
  const user = searchParamsCache.get('user');
  const moduleName = searchParamsCache.get('module');
  const action = searchParamsCache.get('action');
  const dateFrom = searchParamsCache.get('dateFrom');
  const dateTo = searchParamsCache.get('dateTo');
  const sort = searchParamsCache.get('sort');

  const filters = {
    page,
    limit: pageLimit,
    ...(search && { search }),
    ...(user && { user }),
    ...(moduleName && { module: moduleName }),
    ...(action && { action }),
    ...(dateFrom && { dateFrom }),
    ...(dateTo && { dateTo }),
    ...(sort && { sort })
  };

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

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