import { create } from 'zustand'
import api from '../api/api'
import { toast } from 'react-hot-toast'
const useCourseStore = create((set, get) => ({
    courses: [],
    isLoading: true,

    getCourses: async () => {
        try {
            const res = await api.get('/courses/all')
            if(res.status == 200) {
                set({ courses: res.data, isLoading: false })
                return res.data
            }
        } catch (error) {
            console.log(error)
        }finally{
            set({ isLoading: false })
        }
    },

    createCourse: async (course_name, duration) => {
        try {
            const res = await api.post('/courses/create', { course_name, duration })
            if(res.status == 201) {
                toast.success(res.data.message)
                await get.getCourses()
                return res.data
            }else{
                toast.error(res.data.message)
            }
            
        } catch (error) {
            console.log(error)
        }
    },
    updateCourse: async (id, course_name, duration) => {
        try {
            const res = await api.put(`/courses/update/${id}`, { course_name, duration })
            if(res.status == 200) {
                toast.success(res.data.message)
                await get.getCourses()
                return res.data
            } else {
                toast.error(res.data.message)
            }
        } catch (error) {
            console.log(error)
        }
    },
    deleteCourse: async (id) => {
        try {
            const res = await api.delete(`/courses/delete/${id}`)
            if(res.status == 200) {
                toast.success(res.data.message)
                await get.getCourses()
                return res.data
            } else {
                toast.error(res.data.message)
            }
        } catch (error) {
            console.log(error)
        }
    },
}))

export default useCourseStore