import { Entry } from 'contentful'
import contentfulClient from './contentfulClient'
import { parseContentfulContentImage } from './contentImage'
import {BlogPost, BlogPostEntry, BlogPostSkeleton} from "../../types/blogPost";
import {parseContentfulAuthor} from "./authors";
import dayjs from "dayjs";
import {WidgetMedia, WidgetMediaEntry} from "../../types/blogWidgets/widgetMedia";
import {WidgetParagraph} from "../../types/blogWidgets/widgetParagraph";
import entry from "next/dist/server/typescript/rules/entry";
import Util from "node:util";
import {DEFAULT_PAGE_SIZE} from "../../constants/common";

const pageSize = DEFAULT_PAGE_SIZE
type PostEntry = BlogPostEntry<undefined, string>//Entry<BlogPostSkeleton, undefined, string>
type widgetEnum = WidgetParagraph | WidgetMedia
export type Widget = {
   widget: widgetEnum
   type: string
}
type WidgetEntry = WidgetMediaEntry<undefined, string> | WidgetParagraph<undefined, string>
function parseWidgets(entries?: Array<WidgetEntry>): Array<Widget> | null {
    if (!entries || !entries.length) {
        return null
    }
    return entries.map((entry: WidgetEntry) => {
        const wType = entry.sys.contentType.sys.id
        let wObj = {} as widgetEnum
        switch (wType){
            case 'widgetParagraph':
                wObj = {
                    subTitle: entry.fields.subTitle,
                    body: entry.fields.body
                }
                break
            case 'widgetMedia':
                wObj = {
                    decription: entry.fields.decription || '',
                    file: parseContentfulContentImage(entry.fields.file)
                }
                break
        }
        return {
            type: wType,
            widget: wObj
        }
    })
}

export function parseContentfulBlogPost(entry?: PostEntry): BlogPost | null {
    if (!entry) {
        return null
    }

    return {
        title: entry.fields.title || '',
        slug: entry.fields.slug,
        excerpt: entry.fields.excerpt || '',
        listImage: parseContentfulContentImage(entry.fields.listImage),
        author: parseContentfulAuthor(entry.fields.author),
        createdAt: dayjs(entry.sys.createdAt).format('MMM DD, YYYY'),
        category: entry.fields.category.fields.title,
        categorySlug: entry.fields.category.fields.slug,
        body: parseWidgets(entry.fields.body) || []
    }
}

interface FetchBlogPostsOptions {
    preview: boolean
    local?: string
    category?: string
    page?: number
    sticky?: boolean
}
export async function fetchBlogPosts({ preview, category, page, sticky }: FetchBlogPostsOptions): Promise<{
    total: number;
    data: BlogPost[]
}> {
    const contentful = contentfulClient({ preview })
    const query = {
        content_type: 'blogPost',
        select: ['fields.title', 'fields.excerpt', 'fields.author', 'fields.listImage', 'fields.author', 'fields.category', 'sys.createdAt', 'fields.slug', 'fields.metaDescription'],
        order: ['sys.createdAt'],
    }
    if (category){
        query['fields.category.fields.slug'] = category
        query['fields.category.sys.contentType.sys.id']='blogPostCategory'
    }


    if(page){
        query['limit'] = pageSize
        query['skip'] = pageSize * (page - 1)
    }

    if (sticky){ // только три для главной
        query['fields.sticky'] = 1
        query['limit'] = 3
        query['skip'] = 0
    }

    const blogPostsResult = await contentful.getEntries<BlogPostSkeleton>(query)

    const data = blogPostsResult.items.map((blogPostEntry) => parseContentfulBlogPost(blogPostEntry) as BlogPost)
    return {
        total: blogPostsResult.total,
        data
    }
}

interface FetchBlogPostOptions {
    slug: string
    preview: boolean
}
export async function fetchBlogPost({ slug, preview }: FetchBlogPostOptions): Promise<BlogPost | null> {
    const contentful = contentfulClient({ preview })

    const blogPostsResult = await contentful.getEntries<BlogPostSkeleton>({
        content_type: 'blogPost',
        'fields.slug': slug,
        include: 2,
    })

    return parseContentfulBlogPost(blogPostsResult.items[0])
}