import axiosInstance from '../../../../utils/axiosInstance';

const sortLevels = (levels) => {
    return levels.sort((a, b) => {
      const getLevelValue = (level) => {
        if (level === 'Pretest' || level === 'PRETEST') return 0; 
        const match = level.match(/level (\d+)/);
        return match ? parseInt(match[1], 10) : Infinity; 
      };
  
      return getLevelValue(a.NAME_LEVEL) - getLevelValue(b.NAME_LEVEL);
    });
};

const fetchLevels = async (topicId) => {
    try {
        const response = await axiosInstance.get(`/level/topic/${topicId}`);
        return response.data;
    } catch (error) {
        return [];
    }
};

// const fetchNextLearning = async (topicId) => {
//     try {
//         const response = await axiosInstance.get(`/level/topic/${topicId}`);
//         return response.data.data.lastCompletedLevel.NEXT_LEARNING;
//     } catch (error) {
//         return [];
//     }
// };

// const fetchLevels = async (next) => {
//     try {
//         const response = await axiosInstance.get(`/previous/level/${next}`);
//         // return response.data;
        
//         const { currentLevel, previousLevels } = response.data.data;
//         const combinedLevels = [currentLevel, ...previousLevels];
//         const sortedLevels = sortLevels(combinedLevels);

//         for (let i = sortedLevels.length; i < 7; i++) {
//             sortedLevels.push({ID_LEVEL: `L00${i}`, IS_PRETEST: 0, SCORE: null});
//         }

//         return {levels: sortedLevels, lastCompletedLevel: response.data.data.currentLevel}

//     } catch (error) {
//         return [];
//     }
// };

// const levelnol =async (next) =>{
//     try {
//         const response = await axiosInstance.get(`/level/topic/${next}`);
//         const levelData = response.data.data.levels;
//         const currentLevel = levelData.filter(level => level.NAME_LEVEL === 'Pretest');

//         for (let i = currentLevel.length; i < 7; i++) {
//             currentLevel.push({ID_LEVEL: `L00${i}`, IS_PRETEST: 0, SCORE: null});
//         }

//         return {levels: currentLevel, lastCompletedLevel: currentLevel};

//     } catch (error) {
//         return error;
//     }
// }

export default {
    fetchLevels, 
    // fetchNextLearning,
    // levelnol,
    // test
};
