import type { SearchParams } from 'nuqs/server';
import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import PageContainer from '@/components/layout/page-container';
import { trainingPoliciesQueryOptions } from '@/features/training-policy/api/queries';
import { TrainingPolicyPage } from '@/features/training-policy/components/training-policy-page';
import { requirePermissionDashboardAccess } from '@/lib/auth/page-guards';
import { getQueryClient } from '@/lib/query-client';
import { searchParamsCache } from '@/lib/searchparams';

type PageProps = {
  searchParams: Promise<SearchParams>;
};

export default async function Page(props: PageProps) {
  const access = await requirePermissionDashboardAccess('training_policy:read');
  const searchParams = await props.searchParams;
  const parsed = searchParamsCache.parse(searchParams);

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

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

  return (
    <PageContainer
      pageTitle='นโยบายการอบรม'
      pageDescription='จัดการเป้าหมายชั่วโมงอบรมรายปีและสถานะนโยบายที่ใช้งานอยู่ขององค์กร'
    >
      <HydrationBoundary state={dehydrate(queryClient)}>
        <TrainingPolicyPage permissions={access.session.user.effectivePermissions} />
      </HydrationBoundary>
    </PageContainer>
  );
}
