import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { notFound } from 'next/navigation';
import PageContainer from '@/components/layout/page-container';
import { onlineLessonByIdOptions } from '@/features/online-lessons/api/queries';
import OnlineLessonForm from '@/features/online-lessons/components/online-lesson-form';
import { requireEmployeeDashboardAccess } from '@/lib/auth/page-guards';
import { getQueryClient } from '@/lib/query-client';

export const metadata = {
  title: 'Dashboard : Edit Online Lesson'
};

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

async function OnlineLessonFormLoader({
  lessonId,
  currentUserId,
  permissions
}: {
  lessonId: number;
  currentUserId: string;
  permissions: readonly string[];
}) {
  const queryClient = getQueryClient();
  const data = await queryClient.fetchQuery(onlineLessonByIdOptions(lessonId));

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <OnlineLessonForm
        initialData={data.online_lesson}
        currentUserId={currentUserId}
        permissions={permissions}
      />
    </HydrationBoundary>
  );
}

export default async function Page(props: PageProps) {
  const access = await requireEmployeeDashboardAccess();
  const { id } = await props.params;
  const lessonId = Number(id);

  if (Number.isNaN(lessonId)) {
    notFound();
  }

  return (
    <PageContainer>
      <OnlineLessonFormLoader
        lessonId={lessonId}
        currentUserId={access.session.user.id}
        permissions={access.session.user.effectivePermissions}
      />
    </PageContainer>
  );
}
