import { create } from "zustand"
import toast from "react-hot-toast"
import api from "../service/api"
const useAuthStore = create((set) => ({
    isLoggedIn: false,
    isCheckingAuth: false,
    user: null,
    login: async(username, password) => {
        try{
            set({ isCheckingAuth: true })
            const res = await api.post("/auth/login", { username, password })
            if(res.status === 200){
                set({ isLoggedIn: true, user: res.data })
                toast.success("Login successful")
                return
            }
        }catch(error){
            console.log(error)
            toast.error(error.response?.data?.message || "Login failed")
        }finally{
            set({ isCheckingAuth: false })
        }
    },
    logout: async() => {
        try{
            set({ isCheckingAuth: true })
            const res = await api.post("/auth/logout")
            if(res.status === 200){
                set({ isLoggedIn: false, user: null })
                toast.success("Logout successful")
                return
            }
        }catch(error){
            console.log(error)
            toast.error(error.response?.data?.message || "Logout failed")
        }finally{
            set({ isCheckingAuth: false })
        }
    },
    register: async(username, password) => {
        try{
            set({ isCheckingAuth: true })
            const res = await api.post("/auth/register", { username, password })
            if(res.status === 201){
                set({ isLoggedIn: true, user: res.data })
                toast.success("Registration successful")
                return
            }
        }catch(error){
            console.log(error)
            toast.error(error.response?.data?.message || "Registration failed")
        }finally{
            set({ isCheckingAuth: false })
        }
    },
    checkAuth: async() => {
        try{
            set({ isCheckingAuth: true })
            const res = await api.get("/auth/check")
            if(res.status === 200){
                set({ isLoggedIn: true, user: res.data })
            }
        }catch(error){
            console.log(error)
            set({ isLoggedIn: false, user: null })
        }finally{
            set({ isCheckingAuth: false })
        }
    }

}))

export default useAuthStore