import matter from 'gray-matter';

export interface BlogPost {
  slug: string;
  title: string;
  date: string;
  description: string;
  image: string;
  content: string;
  keywords?: string;
  author?: string;
}

export function useBlog() {
  const getPosts = async (): Promise<BlogPost[]> => {
    const modules = import.meta.glob('../blog/*.md', { query: '?raw', import: 'default' });
    const posts: BlogPost[] = [];

    for (const path in modules) {
      const content = (await modules[path]()) as string;
      const { data, content: markdownContent } = matter(content);
      const slug = path.split('/').pop()?.replace('.md', '') || '';

      posts.push({
        slug,
        title: data.title,
        date: data.date,
        description: data.description,
        image: data.image,
        content: markdownContent,
        keywords: data.keywords,
        author: data.author,
      });
    }

    return posts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  };

  const getPost = async (slug: string): Promise<BlogPost | undefined> => {
    const posts = await getPosts();
    return posts.find(post => post.slug === slug);
  };

  return {
    getPosts,
    getPost,
  };
}
