import {
    dehydrate,
    HydrationBoundary,
    QueryClient,
} from "@tanstack/react-query";
import PageBody from "@/app/deals/components/shared/PageBody/PageBody";
import { BoardsContextProvider } from "@/app/deals/contexts/BoardsContext";
import { ProjectsContextProvider } from "@/app/deals/contexts/ProjectsContext";
import { StatusesContextProvider } from "@/app/deals/contexts/StatusesContext";
import { ViewContextProvider } from "@/app/deals/contexts/ViewContext";
import PageBlock from "@/components/layout/PageBlock/PageBlock";
import PageContainer from "@/components/layout/PageContainer/PageContainer";
import {
    getBoardsOptions,
    getProjectsOptions,
} from "@/lib/client/@tanstack/react-query.gen";
import { combineProviders } from "@/utils/combineProviders";
import TopToolPanel from "./components/desktop/TopToolPanel/TopToolPanel";

async function prefetchData() {
    const queryClient = new QueryClient();
    const projectsData = await queryClient.fetchQuery(getProjectsOptions());

    const firstProjectId = projectsData.projects?.[0]?.id;
    if (!firstProjectId) return queryClient;

    await queryClient.prefetchQuery(
        getBoardsOptions({ path: { projectId: firstProjectId } })
    );

    return queryClient;
}

export default async function DealsPage() {
    const queryClient = await prefetchData();

    const Providers = combineProviders(
        [HydrationBoundary, { state: dehydrate(queryClient) }],
        [ProjectsContextProvider],
        [BoardsContextProvider],
        [StatusesContextProvider],
        [ViewContextProvider]
    );

    return (
        <Providers>
            <PageContainer>
                <TopToolPanel />
                <PageBlock>
                    <PageBody />
                </PageBlock>
            </PageContainer>
        </Providers>
    );
}
