import ChapterDetailPage from "@/components/novel/detail/chapter/chapterDetailPage";
import { getChapterDetailAuthenticated } from "@/libs/axios/modules/chapter";
import { getPostChapters, getPostChaptersAuthenticated, getPostDetail, getPostDetailAuthenticated } from "@/libs/axios/modules/post";
import { ChapterModel, PostModel } from "@/models";
import { extractId } from "@/utils/slug";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

export default async function Page({
    params,
}: {
    params: Promise<{ locale: string; novel_id: string; chapter_id: string }>;
}) {
    const cookieStore = await cookies();
    const token = cookieStore.get("token");
    const rawToken = token?.value?.slice(1, -1);

    const { novel_id: novelIdParam, chapter_id: chapterIdParam } = await params;
    const novel_id = extractId(novelIdParam);
    const chapter_id = extractId(chapterIdParam);

    if (!rawToken) redirect("/login");

    try {
        const [chapterRes, novelRes, chaptersRes] = await Promise.all([
            getChapterDetailAuthenticated(rawToken, chapter_id),
            rawToken ? getPostDetailAuthenticated(rawToken, novel_id) : getPostDetail(novel_id),
            rawToken
                ? getPostChaptersAuthenticated(rawToken, { post_id: novel_id, limit: 0 })
                : getPostChapters(novel_id, { limit: 0 }),
        ]);

        const chapter: ChapterModel = chapterRes.data.data;
        const novel: PostModel = novelRes.data.data;
        const rawChapters: ChapterModel[] = chaptersRes.data.data;

        const chapters = rawChapters.map((c) => ({
            ...c,
            is_paid: c.order > 5,
        }));

        return (
            <ChapterDetailPage
                chapter={chapter}
                chapters={chapters}
                novel={novel}
                token={rawToken}
            />
        );
    } catch {
        redirect(`/novel/${novelIdParam}`);
    }
}