"use client";

import { create } from "zustand";

const useUserStore = create((set) => ({
  user: null,
  loading: true,
  error: null,
  fetched: false,

  setUser: (user) => set({ user, loading: false, fetched: true }),

  clearUser: () => set({ user: null, loading: false, fetched: true }),

  setLoading: (loading) => set({ loading }),

  setError: (error) => set({ error, loading: false, fetched: true }),

  fetchUser: async () => {
    set({ loading: true, error: null });
    try {
      const res = await fetch("/api/auth/me");
      const data = await res.json();
      if (data.authenticated && data.user) {
        set({ user: data.user, loading: false, fetched: true });
      } else {
        set({ user: null, loading: false, fetched: true });
      }
    } catch (err) {
      set({ user: null, loading: false, fetched: true, error: err.message });
    }
  },
}));

export default useUserStore;

