import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { notFound, redirect } from 'next/navigation';
import PageContainer from '@/components/layout/page-container';
import { announcementByIdOptions } from '@/features/announcements/api/queries';
import AnnouncementViewPage from '@/features/announcements/components/announcement-view-page';
import { hasAnyPermission } from '@/lib/auth/authorization';
import { requireEmployeeDashboardAccess } from '@/lib/auth/page-guards';
import { getQueryClient } from '@/lib/query-client';

export const metadata = {
  title: 'Dashboard : Announcement Detail'
};

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

export default async function Page(props: PageProps) {
  const access = await requireEmployeeDashboardAccess();
  const params = await props.params;
  const permissions = access.session.user.effectivePermissions;
  const canCreateAnnouncements = hasAnyPermission(permissions, ['announcement:create']);

  if (params.id === 'new' && !canCreateAnnouncements) {
    redirect('/dashboard/announcements');
  }

  if (params.id !== 'new' && Number.isNaN(Number(params.id))) {
    notFound();
  }

  const queryClient = getQueryClient();

  if (params.id !== 'new') {
    await queryClient.fetchQuery(announcementByIdOptions(Number(params.id)));
  }

  return (
    <PageContainer>
      <HydrationBoundary state={dehydrate(queryClient)}>
        <AnnouncementViewPage
          announcementId={params.id}
          currentUserId={access.session.user.id}
          permissions={permissions}
        />
      </HydrationBoundary>
    </PageContainer>
  );
}
