import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface IndicatorInstance {
  id: string
  talib_name: string
  instance_name: string
  parameters: Record<string, any>
  tv_study_id?: string
  tv_indicator_name?: string
  tv_inputs?: Record<string, any>
  visible: boolean
  pane: string
  symbol?: string
  created_at?: number
  modified_at?: number
  original_id?: string
}

export const useIndicatorStore = defineStore('IndicatorStore', () => {
  const indicators = ref<Record<string, IndicatorInstance>>({})

  // Helper methods
  const addIndicator = (indicator: IndicatorInstance) => {
    indicators.value[indicator.id] = indicator
  }

  const updateIndicator = (id: string, updates: Partial<IndicatorInstance>) => {
    if (indicators.value[id]) {
      const updated = {
        ...indicators.value[id],
        ...updates,
        modified_at: Math.floor(Date.now() / 1000)
      }
      indicators.value[id] = updated
    }
  }

  const removeIndicator = (id: string) => {
    delete indicators.value[id]
  }

  const getIndicator = (id: string): IndicatorInstance | undefined => {
    return indicators.value[id]
  }

  const getAllIndicators = (): IndicatorInstance[] => {
    return Object.values(indicators.value)
  }

  const getIndicatorsBySymbol = (symbol: string): IndicatorInstance[] => {
    return Object.values(indicators.value).filter(ind => ind.symbol === symbol)
  }

  return {
    indicators,
    addIndicator,
    updateIndicator,
    removeIndicator,
    getIndicator,
    getAllIndicators,
    getIndicatorsBySymbol
  }
})
