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

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

    createStudent: async (first_name, last_name, gender, email, phone, course_id) => {
        try {
            const res = await api.post('/students/create', { first_name, last_name, gender, email, phone, course_id })
            if(res.status == 201) {
                toast.success(res.data.message)
                await get.getStudents()
                return res.data
            }else{
                toast.error(res.data.message)
            }
        } catch (error) {
            console.log(error)
        }
    },
    updateStudent: async (id, first_name, last_name, gender, email, phone, course_id) => {
        try {
            const res = await api.put(`/students/update/${id}`, { first_name, last_name, gender, email, phone, course_id })
            if(res.status == 200) {
                toast.success(res.data.message)
                await get.getStudents()
                return res.data
            } else {
                toast.error(res.data.message)
            }
        } catch (error) {
            console.log(error)
        }
    },
    deleteStudent: async (id) => {
        try {
            const res = await api.delete(`/students/delete/${id}`)
            if(res.status == 200) {
                toast.success(res.data.message)
                await get.getStudents()
                return res.data
            } else {
                toast.error(res.data.message)
            }
        } catch (error) {
            console.log(error)
        }
    },
}))

export default useStudentStore