import { create } from 'zustand'
import type { AssistantContext, AssistantMessage } from '../domain/assistant'

interface AssistantState {
  isOpen: boolean
  context: AssistantContext | null
  messages: AssistantMessage[]
  isLoading: boolean
  error: string | null

  open: () => void
  close: () => void
  setContext: (ctx: AssistantContext) => void
  updateContext: (partial: Partial<AssistantContext>) => void
  addMessage: (msg: AssistantMessage) => void
  setLoading: (v: boolean) => void
  setError: (e: string | null) => void
  clearConversation: () => void
}

export const useAssistantStore = create<AssistantState>((set) => ({
  isOpen: false,
  context: null,
  messages: [],
  isLoading: false,
  error: null,

  open: () => set({ isOpen: true }),
  close: () => set({ isOpen: false }),
  setContext: (ctx) => set({ context: ctx }),
  updateContext: (partial) => set((s) => ({ context: s.context ? { ...s.context, ...partial } : null })),
  addMessage: (msg) => set((s) => ({ messages: [...s.messages, msg] })),
  setLoading: (v) => set({ isLoading: v }),
  setError: (e) => set({ error: e }),
  clearConversation: () => set({ messages: [], error: null }),
}))
