import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import {
  certificatesQueryOptions,
  userOptionsQueryOptions,
  trainingRecordByIdOptions
} from '@/features/training-records/api/queries';
import PageContainer from '@/components/layout/page-container';
import TrainingRecordViewPage from '@/features/training-records/components/training-record-view-page';
import { isHRD } from '@/lib/auth/roles';
import { requireEmployeeDashboardAccess } from '@/lib/auth/page-guards';

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

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

export default async function Page(props: PageProps) {
  const access = await requireEmployeeDashboardAccess();

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

  if (
    isHRD({
      businessRole: access.session.user.businessRole,
      systemRole: access.session.user.systemRole,
      membershipRole: access.membership.role,
      role: access.session.user.role
    })
  ) {
    prefetchTasks.push(queryClient.fetchQuery(userOptionsQueryOptions()));
  }

  if (params.trainingRecordId !== 'new') {
    const trainingRecordId = Number(params.trainingRecordId);
    prefetchTasks.push(queryClient.fetchQuery(trainingRecordByIdOptions(trainingRecordId)));
    prefetchTasks.push(queryClient.fetchQuery(certificatesQueryOptions(trainingRecordId)));
  }

  await Promise.all(prefetchTasks);

  return (
    <PageContainer>
      <div className='flex-1 space-y-4'>
        <HydrationBoundary state={dehydrate(queryClient)}>
          <TrainingRecordViewPage
            trainingRecordId={params.trainingRecordId}
            currentUser={{
              id: access.session.user.id,
              name: access.session.user.name ?? access.session.user.email ?? 'Current user',
              employeeId: access.session.user.employeeId
            }}
            businessRole={access.session.user.businessRole}
            systemRole={access.session.user.systemRole}
          />
        </HydrationBoundary>
      </div>
    </PageContainer>
  );
}
