import { create } from 'zustand';
import { secureStorage } from '../../../core/infrastructure/secureStore';
import { connectSocket, disconnectSocket } from '../../../core/infrastructure/socket';
import { PushService } from '../../../core/infrastructure/pushService';

// Fallback types if domain is not yet copied
interface User {
  id: string;
  username: string;
  displayName: string;
}

interface AuthState {
  token: string | null;
  user: User | null;
  isLoading: boolean;
  error: string | null;
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
  initialize: () => Promise<void>;
}

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

  initialize: async () => {
    try {
      const token = await secureStorage.getItem('knot_token');
      if (token) {
        // Here you would typically call an API to verify the token and get user info
        // For now, mirroring web logic slightly
        set({ token, isLoading: false });
        connectSocket(token);
        
        // Register for push notifications after login
        const pushToken = await PushService.registerForPushNotificationsAsync();
        if (pushToken) {
          console.log('Push Token:', pushToken);
          // TODO: Send pushToken to backend: await AuthApi.sendPushToken(pushToken);
        }
      } else {
        set({ isLoading: false });
      }
    } catch (err) {
      set({ isLoading: false });
    }
  },

  login: async (username, password) => {
    try {
      set({ isLoading: true, error: null });
      
      // Mocking API call - in reality, use adapted AuthApi
      const mockResult = { token: 'mock-token', user: { id: '1', username, displayName: username } };
      
      await secureStorage.setItem('knot_token', mockResult.token);
      connectSocket(mockResult.token);
      
      set({ token: mockResult.token, user: mockResult.user, isLoading: false });
      
      const pushToken = await PushService.registerForPushNotificationsAsync();
      // TODO: send to server
    } catch (err: any) {
      set({ isLoading: false, error: err.message });
    }
  },

  logout: async () => {
    await secureStorage.removeItem('knot_token');
    disconnectSocket();
    set({ token: null, user: null });
  },
}));
