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

const useAuthStore = create((set) => ({
    user: null,
    isLoggedIn: false,
    login: async (username, password) => {
        try {
            const res = await api.post("/auth/login", { username, password })
            if (res.status === 200) {
                set({ user: res.data, isLoggedIn: true })
                toast.success(res.data.message)
                return true
            }

            toast.error(res.data?.message || "Login failed")
            return false
        } catch (error) {
            const msg = error?.response?.data?.message || error?.message || "Login failed"
            toast.error(msg)
            console.log(error)
            return false
        }
    },
    register: async(username, password) => {
        try {
            const res = await api.post("/auth/register", { username, password })
            if(res.status == 201){
                toast.success(res.data.message)
            }else{
                toast.error(res.data.message)
            }
            
        } catch (error) {
            console.log(error)
        }
    },
    logout: async() => {
        try {
            const res = await api.post("/auth/logout")
            if(res.status == 200){
                set({ user: null, isLoggedIn: false })
                toast.success(res.data.message)
            }else{
                toast.error(res.data.message)
            }
        } catch (error) {
            console.log(error)
        }
    },
    checkAuth: async() => {
        try {
            const res = await api.get("/auth/check")
            if(res.status == 200){
                set({ user: res.data, isLoggedIn: true })
            }
        } catch (error) {
            console.log(error)
        }
    }
}))

export default useAuthStore