// postsCache.js
// Caching layer for blog post data
// Prevents multiple simultaneous API calls and provides efficient data access
import { loadPosts } from './blog-post-data';

// Cache state management
let postsCache = null;
let isLoading = false;
let loadPromise = null;

// Singleton pattern with promise deduplication for efficient data loading
export const getPosts = async () => {
    // Return cached data immediately if available
    if (postsCache) {
        return postsCache;
    }

    // Prevent duplicate loading - wait for existing promise
    if (isLoading && loadPromise) {
        return loadPromise;
    }

    // Start loading process with promise caching
    isLoading = true;
    loadPromise = loadPosts().then(posts => {
        postsCache = posts;
        isLoading = false;
        return posts;
    });

    return loadPromise;
};

// Filter published posts for dashboard display
export const getPublishedPosts = async () => {
    const posts = await getPosts();
    return posts.filter(post => post.published);
};

// Filter draft posts for editor management
export const getDraftPosts = async () => {
    const posts = await getPosts();
    return posts.filter(post => !post.published);
};

// Find specific post by slug for editor functionality
export const getPostBySlug = async (slug) => {
    const posts = await getPosts();
    return posts.find(post => post.slug === slug);
};
