import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';
import { announcementsQueryOptions } from '../api/queries';
import type { AnnouncementStatus } from '../api/types';
import AnnouncementsPage from './announcements-page';

export default async function AnnouncementsListingPage({
  currentUserId,
  permissions
}: {
  currentUserId: string;
  permissions: readonly string[];
}) {
  const page = searchParamsCache.get('page');
  const perPage = searchParamsCache.get('perPage');
  const search = searchParamsCache.get('search');
  const status = searchParamsCache.get('status');
  const pin = searchParamsCache.get('pin');
  const sort = searchParamsCache.get('sort');

  const filters = {
    page,
    limit: perPage,
    ...(search && { search }),
    ...(status && { status: status as AnnouncementStatus }),
    ...(pin && { pin: pin as 'all' | 'pinned' }),
    ...(sort && { sort })
  };

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

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