import { create } from 'zustand';
import type { Ticker, OrderBook, Trade } from '../types/models';

interface MarketState {
  // Data
  tickers: Record<string, Ticker>;
  orderBook: Record<string, OrderBook>;
  recentTrades: Trade[];

  // Connection state
  isConnected: boolean;

  // Actions
  setTicker: (ticker: Ticker) => void;
  setOrderBook: (orderBook: OrderBook) => void;
  addRecentTrade: (trade: Trade) => void;
  setConnectionStatus: (connected: boolean) => void;
  clearData: () => void;
}

const MAX_TRADES_HISTORY = 1000;

export const useMarketStore = create<MarketState>((set) => ({
  // Initial state
  tickers: {},
  orderBook: {},
  recentTrades: [],
  isConnected: false,

  // Actions
  setTicker: (ticker) =>
    set((state) => ({
      tickers: {
        ...state.tickers,
        [ticker.symbol]: ticker,
      },
    })),

  setOrderBook: (orderBook) =>
    set((state) => ({
      orderBook: {
        ...state.orderBook,
        [orderBook.symbol]: orderBook,
      },
    })),

  addRecentTrade: (trade) =>
    set((state) => {
      // Check if trade already exists
      const exists = state.recentTrades.some((t) => t.id === trade.id);
      if (exists) return state;

      // Add new trade at the beginning and limit history
      const newTrades = [trade, ...state.recentTrades].slice(0, MAX_TRADES_HISTORY);

      return {
        recentTrades: newTrades,
      };
    }),

  setConnectionStatus: (connected) =>
    set(() => ({
      isConnected: connected,
    })),

  clearData: () =>
    set(() => ({
      tickers: {},
      orderBook: {},
      recentTrades: [],
    })),
}));
