// zustand/userStore.ts
import { create } from 'zustand'
import { persist } from 'zustand/middleware'

type User = {
  id: string
  name: string
  number: string
  accessToken: string
  refreshToken: string
}

type AuthStore = {
  user: User | null
  isAuthenticated: boolean
  login: (userData: User) => void
  logout: () => void
  update: (userData: User) => void
  setToken: (token: string | null) => void;
}

export const useAuthStore = create<AuthStore>()(
  persist(
    (set) => ({
      user: null,
      isAuthenticated: false,
      login: (userData) =>
        set(() => ({
          user: userData,
          isAuthenticated: true,
        }))
      ,
      logout: () =>
        set(() => ({
          user: null,
          isAuthenticated: false,
        })),
      update: (userData) => {
        set((state) => {
          if (!state.user) return state; // no user to update
          return {
            user: {
              ...state.user,
              ...userData
            },
          };
        });
      },
      setToken: (token) => {
        set((state) => {
          if (!state.user) return state; // no user to update
          return {
            user: {
              ...state.user,
              accessToken: token ?? '',
            },
          };
        });
      }
    }),
    {
      name: 'auth-storage', // Key in localStorage
    }
  )
)
