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

export interface ControlPoint {
  time: number
  price: number
  channel?: string
}

export interface Shape {
  id: string
  type: string
  points: ControlPoint[]
  color?: string
  line_width?: number
  line_style?: string
  properties?: Record<string, any>
  symbol?: string
  created_at?: number
  modified_at?: number
  original_id?: string  // Original ID from backend/agent before TradingView assigns its own ID
}

export const useShapeStore = defineStore('ShapeStore', () => {
  const shapes = ref<Record<string, Shape>>({})

  // Helper methods
  const addShape = (shape: Shape) => {
    shapes.value[shape.id] = shape
  }

  const updateShape = (id: string, updates: Partial<Shape>) => {
    if (shapes.value[id]) {
      const updated = {
        ...shapes.value[id],
        ...updates,
        modified_at: Math.floor(Date.now() / 1000)
      }
      // Replace the entire shape object to ensure arrays are replaced atomically
      shapes.value[id] = updated
    }
  }

  const removeShape = (id: string) => {
    delete shapes.value[id]
  }

  const getShape = (id: string): Shape | undefined => {
    return shapes.value[id]
  }

  const getAllShapes = (): Shape[] => {
    return Object.values(shapes.value)
  }

  return {
    shapes,
    addShape,
    updateShape,
    removeShape,
    getShape,
    getAllShapes
  }
})
