import { create } from "zustand";
import { persist } from "zustand/middleware";
import { AuthState, User } from "@/lib/types/user";

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      loading: false,
      error: null,

      setUser: (user: User | null) => set({ user }),
      setToken: (token: string | null) => set({ token }),
      setLoading: (loading: boolean) => set({ loading }),
      setError: (error: string | null) => set({ error }),

      logout: () => set({ user: null, token: null, error: null }),

      isAuthenticated: () => !!get().user,
    }),
    {
      name: "auth-storage",

      partialize: (state) => ({
        user: state.user,
        token: state.token,
      }),
    }
  )
);
