import api from "../service/api"
import { create } from "zustand"
import toast from "react-hot-toast"
const useStudentStore = create((set, get) => ({
    students: [],
    student: null,
    getStudents: async() => {
        try{
            const res = await api.get("/student/all")
            if(res.status === 200){
                set({ students: res.data.students })
            }
        }catch(error){
            console.log(error)
        }
    },
    getStudent: async(id) => {
        try{
            const res = await api.get(`/student/${id}`)
            if(res.status === 200){
                set({ student: res.data })
            }
        }catch(error){
            console.log(error)
        }
    },
    addStudent: async(student) => {
        try{
            const res = await api.post("/student/add", student)
            if(res.status === 201){
                toast.success("Student added successfully")
                set({ students: [...get().students, res.data.student] })
                return
            }
        }catch(error){
            console.log(error)
            toast.error(error.response?.data?.message || "Failed to add student")
        }
    },
    deleteStudent: async(id) => {
        try{
            const res = await api.delete(`/student/delete/${id}`)
            if(res.status === 200){
                toast.success("Student deleted successfully")
                set({ students: get().students.filter(student => student._id !== id) })
                return
            }
        }catch(error){
            console.log(error)
            toast.error(error.response?.data?.message || "Failed to delete student")
        }
    },
    editStudent: async(id, student) => {
        try{
            const res = await api.put(`/student/edit/${id}`, student)
            if(res.status === 200){
                toast.success("Student updated successfully")
                await get().getStudents()
                return
            }
        }catch(error){
            console.log(error)
            toast.error(error.response?.data?.message || "Failed to update student")
        }
    }
}))

export default useStudentStore