import directus from './directus';
import { readItems, type Query } from '@directus/sdk';
import type { CodyopsCareers, Careers } from '../types/codyops-careers';
import { sumTimes } from '../utils/time';

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

export async function getCareers(): Promise<Careers[]> {
  const careers = await directus.request(
    readItems<CodyopsCareers, 'codyops_careers', Query<CodyopsCareers, Careers>>('codyops_careers', {
      fields: [
        'slug',
        'status',
        'name',
        'description',
        'banner',
        {
          courses: [
            {
              codyops_courses_id: [
                'name',
                'level',
                'category',
                {
                  modules: [
                    'duration'
                  ]
                }
              ],
            },
          ],
        },
      ],
      filter: {
        status: isDev ? { '_neq': 'archived' } : { '_eq': 'published' }
    },    
    })
  );

  const careersWithCalculatedHours = careers.map(career => {
    let totalCareerMinutes = 0;

        const coursesWithCalculatedHours = career.courses.map(courseItem => {
          const course = courseItem.codyops_courses_id;
          if (course && course.modules) {
            const moduleDurations = course.modules
              .map(module => module.duration)
              .filter((duration): duration is string => duration !== undefined && duration !== null); // Filter out undefined/null
            const { hours, minutes } = sumTimes(moduleDurations);
            const totalCourseMinutes = (hours * 60) + minutes;
            totalCareerMinutes += totalCourseMinutes;
            return {
              ...courseItem,
              codyops_courses_id: {
                ...course,
                totalCourseHours: hours + (minutes / 60), // Store as decimal hours
                totalCourseMinutes: totalCourseMinutes,
              }
            };
          }
          return courseItem;
        });

    const totalCareerHours = Math.floor(totalCareerMinutes / 60);
    const remainingCareerMinutes = totalCareerMinutes % 60;

    return {
      ...career,
      courses: coursesWithCalculatedHours,
      totalCareerHours: totalCareerHours + (remainingCareerMinutes / 60), // Store as decimal hours
      totalCareerMinutes: totalCareerMinutes,
    };
  });

  return careersWithCalculatedHours;
}
