import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import {
  trainingMatrixByIdOptions,
  trainingMatrixOptionsQueryOptions
} from '@/features/training-matrix/api/queries';
import PageContainer from '@/components/layout/page-container';
import TrainingMatrixViewPage from '@/features/training-matrix/components/training-matrix-view-page';
import { requirePermissionDashboardAccess } from '@/lib/auth/page-guards';

export const metadata = {
  title: 'Dashboard : Training Matrix View'
};

type PageProps = { params: Promise<{ matrixId: string }> };

export default async function Page(props: PageProps) {
  await requirePermissionDashboardAccess('training_matrix:write');

  const params = await props.params;
  const queryClient = getQueryClient();
  const prefetchTasks: Array<Promise<unknown>> = [
    queryClient.fetchQuery(trainingMatrixOptionsQueryOptions())
  ];

  if (params.matrixId !== 'new') {
    prefetchTasks.push(queryClient.fetchQuery(trainingMatrixByIdOptions(Number(params.matrixId))));
  }

  await Promise.all(prefetchTasks);

  return (
    <PageContainer>
      <div className='flex-1 space-y-4'>
        <HydrationBoundary state={dehydrate(queryClient)}>
          <TrainingMatrixViewPage matrixId={params.matrixId} />
        </HydrationBoundary>
      </div>
    </PageContainer>
  );
}
