import api from "../service/api"
import { create } from "zustand"
import toast from "react-hot-toast"

const usePaymentStore = create((set, get) => ({
    payments: [],
        getPayments: async() => {
        try{
            const res = await api.get("/payment/all")
            if(res.status === 200){
                set({ payments: res.data.payments })
            }
        }catch(error){
            console.log(error)
        }
    },
    addPayment: async(payment) => {
        try{
            const res = await api.post("/payment/add", payment)
            if(res.status === 201){
                toast.success("Payment added successfully")
                getPayments()
                return
            }
        }catch(error){
            console.log(error)
            toast.error(error.response?.data?.message || "Failed to add payment")
        }
    },
    deletePayment: async(id) => {
        try{
            const res = await api.delete(`/payment/delete/${id}`)
            if(res.status === 200){
                toast.success("Payment deleted successfully")
                set({ payments: get().payments.filter(payment => payment._id !== id) })
                return
            }
        }catch(error){
            console.log(error)
            toast.error(error.response?.data?.message || "Failed to delete payment")
        }
    },
    editPayment: async(id, payment) => {
        try{
            const res = await api.put(`/payment/${id}`, payment)
            if(res.status === 200){
                toast.success("Payment updated successfully")
                set({ payments: get().payments.map(p => p._id === id ? res.data.payment : p) })
                return
            }
        }catch(error){
            console.log(error)
            toast.error(error.response?.data?.message || "Failed to update payment")
        }
    }

}))
export default usePaymentStore