import { create } from 'zustand'

type CaptureMode = 'NONE' | 'INPUT' | 'OUTPUT' | 'BOTH'

interface TracingState {
  /** Key: applicationId → { processorId: captureMode } */
  tracedProcessors: Record<string, Record<string, CaptureMode>>
  isTraced: (app: string, processorId: string) => boolean
  /** Toggle processor tracing (BOTH on, remove on off). Returns the full map for the app. */
  toggleProcessor: (app: string, processorId: string) => Record<string, CaptureMode>
  /** Sync store with server-side config (called when config is fetched). */
  syncFromServer: (app: string, tracedProcessors: Record<string, string>) => void
}

export const useTracingStore = create<TracingState>((set, get) => ({
  tracedProcessors: {},

  isTraced: (app, processorId) =>
    processorId in (get().tracedProcessors[app] ?? {}),

  toggleProcessor: (app, processorId) => {
    const current = { ...(get().tracedProcessors[app] ?? {}) }
    if (processorId in current) delete current[processorId]
    else current[processorId] = 'BOTH'
    set((state) => ({
      tracedProcessors: { ...state.tracedProcessors, [app]: current },
    }))
    return current
  },

  syncFromServer: (app, serverMap) => {
    const mapped: Record<string, CaptureMode> = {}
    for (const [k, v] of Object.entries(serverMap)) {
      mapped[k] = v as CaptureMode
    }
    set((state) => ({
      tracedProcessors: { ...state.tracedProcessors, [app]: mapped },
    }))
  },
}))
