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


const useAuthStore = create((set, get) => ({
    authUser: null,
    isLoading: true,

    checkAuth: async () => {
        try {
            const res = await api.get('/auth/check')
            if(res.status == 200) {
                set({ authUser: res.data, isLoading: false })
                return res.data
            }
        } catch (error) {
            console.log(error)
        }finally{
            set({ isLoading: false })
        }
    },
    logout: async () => {
        try {
            const res = await api.get('/auth/logout')
            if(res.status == 200) {
                set({ authUser: null, isLoading: false })
                toast.success(res.data.message)
            }else{
                toast.error(res.data.message)
            }
        } catch (error) {
            console.log(error)
        }
    },
    login: async (username, password) => {
        try {
            const res = await api.post('/auth/login', { username, password })
            if(res.status == 200) {
                const authUser = await get.checkAuth()
                toast.success(res.data.message)
                return authUser
            } else {
                toast.error(res.data.message)
            }
        } catch (error) {
            console.log(error)
        }
    },
    register: async (username, email, password) => {
        try {
            const res = await api.post('/auth/register', { username, email, password })
            if(res.status == 201) {
                toast.success(res.data.message)
                return res.data
            }else{
                toast.error(res.data.message)
            }
        } catch (error) {
            console.log(error)
        }
    }
}))


export default useAuthStore