import directus from "./directus";
import { readItems, type Query } from "@directus/sdk";
import type { Post, DirectusSchema } from "../types/codyops-post";

const isDev = import.meta.env.DEV; // Astro's way to check for development mode

export const posts = await directus.request(
    readItems<DirectusSchema, 'codyops_posts', Query<DirectusSchema, Post>>("codyops_posts", {
        fields: [
            'slug',
            'status',
            'sort',
            'user_created',
            'user_updated',
            'date_created',
            'date_updated',
            'title',
            'description',
            'tags',
            'cover_image',
            'content'
        ],
        filter: {
            status: isDev ? { '_neq': 'archived' } : { '_eq': 'published' }
        }
    })
);

export function getAllPosts() {
    return posts;
};

export function getUniqueTags(posts: any ) {
    const allTags = posts.flatMap((post: any) => post.tags);
    const uniqueTags = [...new Set(allTags)];
    return uniqueTags;
};
  
export function filterPostsByTag(posts: any, tag: any) {
    return posts.filter((post: any) => post.tags.includes(tag));
};
