import { PublicLayout } from "@/components/layout/public/public-layout";
import { Metadata } from "next";
import { notFound } from "next/navigation";
import { Article, transformPostToArticle } from "@/features/posts/_lib/transformers";
import { nuqsTransformServerSchema } from "@/lib/utils/nuqs-transform-server-schema";
import { createCaller, createHelpers } from "@/lib/trpc/server";
import { PostType } from "@/config/enums";
import { PostFrontendQuerySchema } from "@/server/modules/post/post.validators";
import { adaptPostToContentData } from "@/lib/meta-tags";
import { buildMetadataFromContent, generateMetaTags } from "@/lib/meta-tags/server";
import KbhPlusPage from "../_components/kbhplus/page";
import CitySpacePage from "../_components/byens-rum/page";
import CityLifePage from "../_components/byens-liv/page";
import CityHousePage from "../_components/byens-bolig/page";

type Props = {
    params: Promise<{ slug: string }>;
    searchParams: Promise<Record<string, string | string[] | undefined>>;
};

const BASE_PATH = "inhold";

export async function generateMetadata({ params }: Props): Promise<Metadata> {
    const slug = (await params).slug;

    const helper = await createHelpers();
    const post = await helper.posts.get.fetch({
        with: ["author", "tags", "primaryTag"],
        slug
    });

    if (!post) {
        return {
            title: "Post Not Found | Magasinet KBH",
            description: "The requested post could not be found."
        };
    }

    const contentData = adaptPostToContentData(post, { basePath: BASE_PATH, slug });
    return await buildMetadataFromContent(contentData);
}

export default async function Page({ params, searchParams }: Props) {
    const { slug } = await params;
    const search = nuqsTransformServerSchema(PostFrontendQuerySchema).parse(await searchParams);

    const helpers = await createHelpers();
    const caller = await createCaller();

    const post = await helpers.posts.get.fetch({
        with: ["author", "content", "tags", "primaryTag", "postMedia"],
        slug
    });

    if (!post) {
        notFound();
    }

    void caller.analytic.view({
        postId: post.id
    });

    const { allowed: hasAccess } = await helpers.auth.checkKbhAccess.fetch({
        accessToken: search.token,
        postId: post.id
    });

    const postData = transformPostToArticle(post);
    const contentData = adaptPostToContentData(post, { basePath: BASE_PATH, slug });
    const { jsonLd } = await generateMetaTags(contentData);

    return (
        <PublicLayout>
            {jsonLd && (
                <script
                    type="application/ld+json"
                    dangerouslySetInnerHTML={{
                        __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c")
                    }}
                />
            )}
            {renderPost(postData, hasAccess)}
        </PublicLayout>
    );
}

const renderPost = (post: Article, hasAccess: boolean) => {
    switch (post.topic) {
        case PostType.KBHPLUS:
            return <KbhPlusPage post={post} hasAccess={hasAccess} />;
        case PostType.CITY_SPACES:
            return <CitySpacePage post={post} />;
        case PostType.CITY_LIFE:
            return <CityLifePage post={post} />;
        case PostType.CITY_HOUSE:
            return <CityHousePage post={post} />;
        default:
            <div>Artikel ikke tilgængelig</div>;
    }
};
