import fs from "fs";
import path from "path";
import matter from "gray-matter";

// Define the directory where your markdown files are stored
const blogDirectory = path.join(process.cwd(), "src", "lib", "data", "inspirations");

export function getBlogSlugs() {
  return fs.readdirSync(blogDirectory).filter((file) => file.endsWith(".md"));
}

export function getBlogBySlug(slug) {
  const realSlug = slug.replace(/\.md$/, "");
  const fullPath = path.join(blogDirectory, `${realSlug}.md`);
  if (!fs.existsSync(fullPath)) {
    return null;
  }
  const fileContents = fs.readFileSync(fullPath, "utf8");
  const {data, content} = matter(fileContents);
  return {slug: realSlug, ...data, content};
}

export function getAllBlogs() {
  const slugs = getBlogSlugs();
  const blogs = slugs.map((slug) => getBlogBySlug(slug)).filter(Boolean);
  // Optionally sort the blogs by date (newest first)
  return blogs.sort((a, b) => new Date(b.date) - new Date(a.date));
}
