---
import type { InferGetStaticParamsType, InferGetStaticPropsType } from 'astro';
import Container from "../../components/container.astro";
import Layout from "../../layouts/Layout.astro";
import AuthorDetailCard from '../../components/AuthorDetailCard.astro';
import { getFeaturedPosts, getAllPosts, getAllAuthors, getSettings, invariant, type Post, type Author } from "@matthiesenxyz/astro-ghostcms/api";
import PostPreviewList from '../../components/PostPreviewList.astro';

export async function cleanPosts(){
  const posts = await getAllPosts();
  const featuredPosts = await getFeaturedPosts();
  if(featuredPosts.posts.length === 0) { 
    const notFeatured = posts;
    return notFeatured; 
  } else {
    const featured = featuredPosts.posts[0]
    const notFeatured = posts.filter((post: Post) => post.id !== featured.id )
    return notFeatured;
  }
}

export async function getStaticPaths() {
  const posts = await cleanPosts();
  const { authors } = await getAllAuthors();
  const settings = await getSettings();

  return authors.map((author: Author) => {
    const filteredPosts = posts.filter((post: Post) =>
      post.authors?.map((author: Author) => author.slug).includes(author.slug)
    );
    return {
      params: { slug: author.slug },
      props: {
        posts: filteredPosts,
        settings,
        author,
      },
    };
  });
}

export type Params = InferGetStaticParamsType<typeof getStaticPaths>;
export type Props = InferGetStaticPropsType<typeof getStaticPaths>;

const { posts, settings, author } = Astro.props;
invariant(settings, "Settings are required");
const title = `Posts by author: ${author.name}`;
const description = `All of the articles we've posted and linked so far under the author: ${author.name}`;
---

<Layout title={title} description={description} settings={settings}>
  <Container>
    <section class="outer">
    <AuthorDetailCard name={author.name} count={author.count?.posts || 0} image={author.profile_image} bio={author.bio} location={author.location} website={author.website} twitter={author.twitter} facebook={author.facebook}/>
    <PostPreviewList posts={posts} settings={settings} />
    </section>
  </Container>
</Layout>
