/* eslint-disable no-useless-catch */
import axiosInstance from '../../../../utils/axiosInstance'

const fetchTopic = async () => {
	try {
		const response = await axiosInstance.get(`/topic`)
		return response.data
	} catch (error) {
		throw error
	}
}

const fetchAllHistory = async () => {
	try {
		const response = await axiosInstance.get(`/learningHistory`)
		const historyData = response.data.payload.history
		const validHistory = historyData.filter(
			history => history.STUDENT_FINISH !== null
		)

		return {
			message: response.data.message,
			payload: validHistory,
			status: response.data.statusCode,
		}
	} catch (error) {
		throw error
	}
}

const fetchHistoryBySection = async section => {
	try {
		const response = await axiosInstance.get(
			`/learningHistory/section/${section}`
		)
		const historyData = response.data.payload.history
		const validHistory = historyData.filter(
			history => history.STUDENT_FINISH !== null
		)

		return {
			message: response.data.message,
			payload: validHistory,
			status: response.data.statusCode,
		}
	} catch (error) {
		return { payload: [] }
	}
}

const fetchHistoryByTopic = async topic => {
	try {
		const response = await axiosInstance.get(`/learningHistory/topic/${topic}`)
		const historyData = response.data.payload.history
		const validHistory = historyData.filter(
			history => history.STUDENT_FINISH !== null
		)

		return {
			message: response.data.message,
			payload: validHistory,
			status: response.data.statusCode,
		}
	} catch (error) {
		return { payload: [] }
	}
}

export default {
	fetchTopic,
	fetchAllHistory,
	fetchHistoryBySection,
	fetchHistoryByTopic,
}
