import { create } from 'zustand';
import { authService, type UserContext } from '@/services/authService';

interface AuthState {
  // User context from backend
  user: UserContext | null;
  // Loading state for initial auth check
  isLoading: boolean;
  // Whether user is authenticated
  isAuthenticated: boolean;
  // Error message if auth failed
  error: string | null;

  // Actions
  login: (returnUrl?: string) => void;
  logout: () => Promise<void>;
  refreshUser: () => Promise<void>;
  clearError: () => void;
}

export const useAuthStore = create<AuthState>((set) => ({
  user: null,
  isLoading: true,
  isAuthenticated: false,
  error: null,

  login: (returnUrl?: string) => {
    authService.login(returnUrl);
  },

  logout: async () => {
    await authService.logout();
    set({ user: null, isAuthenticated: false });
  },

  refreshUser: async () => {
    set({ isLoading: true, error: null });
    try {
      const user = await authService.refreshUserContext();
      set({
        user,
        isAuthenticated: user !== null,
        isLoading: false,
      });
    } catch (error) {
      set({
        user: null,
        isAuthenticated: false,
        isLoading: false,
        error: error instanceof Error ? error.message : 'Authentication failed',
      });
    }
  },

  clearError: () => set({ error: null }),
}));

// Selector hooks for convenience
export const useUser = () => useAuthStore((state) => state.user);
export const useIsAuthenticated = () => useAuthStore((state) => state.isAuthenticated);
export const useAuthLoading = () => useAuthStore((state) => state.isLoading);
