import { PostMetadata } from "@/types";
import fs from "fs";
import matter from "gray-matter";
import path from 'path'

const getPostMetadata = (): PostMetadata[] => {
  const folder = path.join(process.cwd(), '/blogs');
  const files = fs.readdirSync(folder);
  const markdownPosts = files.filter((file) => file.endsWith(".md"));

  // Get gray-matter data from each file.
  const posts = markdownPosts.map((fileName) => {
    const fileContents = fs.readFileSync(`blogs/${fileName}`, "utf8");
    const matterResult = matter(fileContents);
    return {
      title: matterResult.data.title,
      date: matterResult.data.date,
      author: matterResult.data.author,
      subtitle: matterResult.data.subtitle,
      slug: fileName.replace(".md", ""),
      image: matterResult.data.image,
    };
  });

  return posts;
};

export default getPostMetadata;
