import { create } from 'zustand'
import { clearToken, clearUser, getToken, getUser, setToken, setUser } from '../utils/storage'
import api from '../services/api'

export const useAuthStore = create((set) => ({
  token: getToken(),
  user: getUser(),
  loading: false,
  isAuthenticated: !!getToken(),
  login: async ({ username, password }) => {
    set({ loading: true })
    try {
      const res = await api.post('/api/auth/login', { username, password })
      const nextToken = res.data.token
      const nextUser = { _id: res.data._id, username: res.data.username }
      setToken(nextToken)
      setUser(nextUser)
      set({ token: nextToken, user: nextUser, isAuthenticated: true })
      return nextUser
    } finally {
      set({ loading: false })
    }
  },
  register: async ({ username, password }) => {
    set({ loading: true })
    try {
      const res = await api.post('/api/auth/register', { username, password })
      const nextToken = res.data.token
      const nextUser = { _id: res.data._id, username: res.data.username }
      setToken(nextToken)
      setUser(nextUser)
      set({ token: nextToken, user: nextUser, isAuthenticated: true })
      return nextUser
    } finally {
      set({ loading: false })
    }
  },
  logout: async () => {
    clearToken()
    clearUser()
    set({ token: null, user: null, isAuthenticated: false })
  },
}))

