import { create } from 'zustand'
import api from '../api/axios'

export const useAuthStore = create((set, get) => ({
  user: null,
  token: null,
  isAuthenticated: false,
  loading: false,

  register: async ({ username, password }) => {
    set({ loading: true })
    try {
      const res = await api.post('/auth/register', { username, password })
      set({ loading: false })
      return res.data
    } catch (err) {
      set({ loading: false })
      throw err
    }
  },

  login: async ({ username, password }) => {
    set({ loading: true })
    try {
      const res = await api.post('/auth/login', { username, password })
      const token = res.data?.token || null
      set({ token, isAuthenticated: true, loading: false, user: { username } })
      return res.data
    } catch (err) {
      set({ loading: false })
      throw err
    }
  },

  logout: async () => {
    set({ loading: true })
    try {
      await api.post('/auth/logout', {})
      set({ user: null, token: null, isAuthenticated: false, loading: false })
    } catch (err) {
      set({ user: null, token: null, isAuthenticated: false, loading: false })
      throw err
    }
  },

  getProfile: async () => {
    set({ loading: true })
    try {
      const res = await api.get('/auth/profile')
      set({ user: res.data?.user || null, isAuthenticated: true, loading: false })
      return res.data
    } catch (err) {
      set({ user: null, token: null, isAuthenticated: false, loading: false })
      throw err
    }
  }
}))

