import { redirect } from "next/navigation";
import { headers } from "next/headers";
import { HydrationBoundary, dehydrate } from "@tanstack/react-query";
import { auth } from "@/lib/auth/auth";
import { Routes } from "@/config/routes";
import { createHelpers } from "@/lib/trpc/server";
import { PublicLayout } from "@/components/layout/public/public-layout";
import { OrganizationListSection } from "@/components/profile/sections/organization-list.section";
import { SubscriptionSection } from "@/components/profile/sections/subscription.section";
import AccountBlock from "./_components/blocks/account-block";
import NewsletterBlock from "./_components/blocks/newsletter-block";
import CommentsBlock from "./_components/blocks/comments-block";
import NewCardBlock from "./_components/blocks/new-card-block";
import LogOutBlock from "./_components/blocks/log-out-block";
import { PlanType } from "@/server/modules/payment/types/plan-type.enum";

export default async function Page() {
    const helpers = await createHelpers();
    const requestHeaders = await headers();

    const [session] = await Promise.all([
        auth.api.getSession({
            headers: requestHeaders
        }),
        helpers.auth.user.prefetch(),
        helpers.organization.list.prefetch({
            with: ["members"]
        }),
        helpers.payment.subscription.list.prefetch({
            with: ["price"],
            planType: PlanType.PERSONAL
        }),
        helpers.payment.subscription.list.prefetch({
            with: ["price"],
            planType: PlanType.BUSINESS
        })
    ]);

    if (!session) {
        return redirect(Routes.AUTH.SIGN_IN);
    }

    const userId = (session.user as { id?: string })?.id;

    return (
        <HydrationBoundary state={dehydrate(helpers.queryClient)}>
            <PublicLayout>
                <AccountBlock user={session.user} />
                <NewsletterBlock user={session.user} />
                <CommentsBlock userId={userId} />
                <OrganizationListSection />
                <SubscriptionSection />
                <NewCardBlock />
                <LogOutBlock />
            </PublicLayout>
        </HydrationBoundary>
    );
}
