"use server";

import { readdirSync, readFileSync } from "fs";
import { join } from "path";
import matter from "gray-matter";

export interface Post {
  slug: string;
  title: string;
  description: string;
  date: string;
  tags?: string[];
}

export async function getPosts(): Promise<Post[]> {
  const postsDir = join(process.cwd(), "src/app/blog/posts");
  const files = readdirSync(postsDir).filter((file) => file.endsWith(".mdx"));

  const posts = files
    .map((file) => {
      const filePath = join(postsDir, file);
      const fileContent = readFileSync(filePath, "utf-8");
      const { data } = matter(fileContent);
      const slug = file.replace(".mdx", "");

      return {
        slug,
        title: data.title || "Untitled",
        description: data.description || "",
        date: data.date || "",
        tags: data.tags || [],
      };
    })
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

  return posts;
}

export async function getPostBySlug(slug: string): Promise<Post | null> {
  const posts = await getPosts();
  return posts.find((post) => post.slug === slug) || null;
}
