import directus from "./directus";
import { readItems, type Query } from "@directus/sdk";
import type { CodyopsCourses, Courses } from "../types/codyops-courses";

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

export const courses = await directus.request(
  readItems<CodyopsCourses, 'codyops_courses', Query<CodyopsCourses, Courses>>("codyops_courses", {
        fields: [
            'id',
            'name',
            'level',
            'category',
            'cloud',
            'image',
            'description',
            'features',
            'status',
            {
              codyops_careers: [
                {
                  codyops_careers_id: [
                    'name',
                    'slug'
                  ]
                }
              ]
            },
            {
                user_created: [
                    'first_name',
                    'last_name',
                    'avatar',
                    'url'
                ]
            },
            {
                modules: [
                    'duration',
                    'title',
                    'description',
                    'video',
                    'status'
                ]
            }
        ],
        filter: {
          status: isDev ? { '_neq': 'archived' } : { '_eq': 'published' }
        },
      }
    )
);

export function getAllCourses() {
    return courses;
};

export function getUniqueCategories(courses: any ) {
    const allCategories = courses.flatMap((course: any) => course.category);
    const uniqueCategories = [...new Set(allCategories)];
    return uniqueCategories;
};

export function filterCoursesByCategory(courses: any, category: any) {
    return courses.filter((course: any) => course.category.includes(category));
};

export function filterCoursesByCloud(courses: any, clouds: string[]) {
    return courses.filter((course: any) => course.cloud?.includes(clouds));
};
