import configPromise from '@payload-config';
import { getPayload } from 'payload';
import type { Where } from 'payload';
import React, { cache } from 'react';

import { CollectionArchive } from '@/components/CollectionArchive';
import { Pagination } from '@/components/Pagination';

type PostsListProps = {
  postType: 'blog' | 'hub';
  page?: number;
  categorySlug?: string;
  title?: string;
};

export async function PostsList({
  postType,
  page = 1,
  categorySlug,
  title: _title,
}: PostsListProps) {
  const payload = await getPayload({ config: configPromise });

  const limit = 15;

  // Build the where clause for post type and category filtering
  const where: Where = {
    postType: {
      equals: postType,
    },
  };

  if (categorySlug) {
    // Fetch the category by slug to get its ID
    const category = await queryCategoryBySlug({ slug: categorySlug });

    if (category) {
      where.categories = {
        contains: category.id,
      };
    }
  }

  const posts = await payload.find({
    collection: 'posts',
    depth: 1,
    limit,
    page,
    overrideAccess: false,
    where,
    select: {
      title: true,
      slug: true,
      categories: true,
      meta: true,
      postType: true,
      updatedAt: true,
    },
  });

  const basePath = postType === 'hub' ? '/hub' : '/blog';
  const categoryBasePath = categorySlug ? `${basePath}/c/${categorySlug}` : basePath;

  return (
    <>
      <CollectionArchive posts={posts.docs} showImage={postType === 'blog'} />

      <div className='container'>
        {posts.totalPages > 1 && posts.page && (
          <Pagination page={posts.page} totalPages={posts.totalPages} basePath={categoryBasePath} />
        )}
      </div>
    </>
  );
}

const queryCategoryBySlug = cache(async ({ slug }: { slug: string }) => {
  const payload = await getPayload({ config: configPromise });

  const categories = await payload.find({
    collection: 'categories',
    where: {
      slug: {
        equals: slug,
      },
    },
    limit: 1,
  });

  return categories.docs[0] || null;
});
