import {create} from 'zustand';
import {persist} from 'zustand/middleware';

const isBrowser = typeof window !== "undefined";

interface AuthData {
  id: number;
  phone: string;
  access_token: string;
}

interface AuthState {
  isAuthenticated: boolean;
  user: AuthData | null;
  login: (data: AuthData) => void;
  logout: () => void;
}

export const useAuthStore = create<AuthState>()(
    persist(
        (set) => ({
          user: isBrowser ? JSON.parse(localStorage.getItem('auth-store') || 'null') : null,
          login: (data) => {
            set({user: data});
            if (isBrowser) {
              localStorage.setItem('auth-store', JSON.stringify(data));
            }
          },
          logout: () => {
            set({user: null});
            if (isBrowser) {
              localStorage.removeItem('auth-store');
            }
          },
          isAuthenticated: isBrowser && localStorage.getItem("auth-store") !== null,
        }),
        {
          name: 'auth-store',
        }
    )
);

