import { NextResponse } from "next/server"
import fs from "fs"
import path from "path"
import matter from "gray-matter"

export interface Post {
  slug: string
  title: string
}

export async function GET() {
  try {
    const postsDirectory = path.join(process.cwd(), "posts")

    // Check if posts directory exists
    if (!fs.existsSync(postsDirectory)) {
      return NextResponse.json([])
    }

    const fileNames = fs.readdirSync(postsDirectory)
    const posts = fileNames
      .filter((name) => name.endsWith(".md") || name.endsWith(".mdx"))
      .map((fileName) => {
        const slug = fileName.replace(/\.(md|mdx)$/, "")
        const fullPath = path.join(postsDirectory, fileName)
        const fileContents = fs.readFileSync(fullPath, "utf8")
        const { data } = matter(fileContents)

        return {
          slug,
          title: data.title || slug,
        }
      })

    return NextResponse.json(posts)
  } catch (error) {
    console.error("Error reading posts:", error)
    return NextResponse.json([])
  }
}
