import glob from "fast-glob";

interface Blog {
  title: string;
  description: string;
  author: {
    name: string;
    src: string;
  };
  date: string;
  image?: string;
}

export interface BlogWithSlug extends Blog {
  slug: string;
}

// Hardcoded blog data to avoid MDX export issues at build time
// This prevents "createContext only works in Client Components" errors
const blogData: Record<string, Blog> = {
  "refactoring-ui-book-review": {
    author: { name: "Alice Johnson", src: "/avatar.webp" },
    date: "2023-11-15",
    title: "Refactoring UI Book Review",
    description: "A comprehensive review of the popular design book 'Refactoring UI' and its practical applications in modern web development.",
    image: "https://images.unsplash.com/photo-1506880018603-83d5b814b5a6?w=800&h=400&fit=crop"
  },
  "rust-vs-go-for-backend": {
    author: { name: "Bob Smith", src: "/avatar.webp" },
    date: "2023-11-10",
    title: "Rust vs Go for Backend Development",
    description: "An in-depth comparison of Rust and Go for building scalable backend services.",
    image: "https://images.unsplash.com/photo-1461749280684-dccba630e2f6?w=800&h=400&fit=crop"
  },
  "best-react-libraries-2024": {
    author: { name: "Charlie Davis", src: "/avatar.webp" },
    date: "2023-11-05",
    title: "Best React Libraries in 2024",
    description: "Discover the most useful React libraries and tools that will boost your productivity in 2024.",
    image: "https://images.unsplash.com/photo-1633356122544-f134324a6cee?w=800&h=400&fit=crop"
  }
};

export async function getAllBlogs() {
  // Still use glob to find existing blog files
  let blogFilenames = await glob("*/page.mdx", {
    cwd: "./app/blog",
  });

  // Map filenames to blog data
  const blogs = blogFilenames.map(filename => {
    const slug = filename.replace(/(\/page)?\.mdx$/, "");
    const blog = blogData[slug];

    if (!blog) {
      // Fallback data if blog not found in hardcoded data
      return {
        slug,
        title: slug.replace(/-/g, " ").replace(/\b\w/g, l => l.toUpperCase()),
        description: "Blog article",
        author: { name: "Author", src: "/avatar.webp" },
        date: new Date().toISOString().split('T')[0],
        image: ""
      };
    }

    return {
      slug,
      ...blog
    };
  });

  return blogs.sort((a, z) => +new Date(z.date) - +new Date(a.date));
}