import { create } from 'zustand'
import { v4 as uuidv4 } from 'uuid'
import type { SimulationResult } from '@/domain/types'
import { supabaseSimulationRepo } from '@/persistence/supabase/simulation-repo'

// Excepción arquitectónica documentada: simulation-store importa process-store en una dirección
// para suscribirse a cambios de datos y invalidar resultados. No existe dependencia inversa.
import { useProcessStore } from '@/store/process-store'

interface SimulationState {
  resultActual: SimulationResult | null
  resultAutomated: SimulationResult | null
  lastSimulatedAt: Date | null
  lastPersistedExecutedAt: number | null
  isRunning: boolean
  error: string | null
  selectedActivityId: string | null

  persistResults: (processId: string, actual: SimulationResult, automated: SimulationResult) => Promise<void>
  setRunning: (running: boolean) => void
  setError: (error: string | null) => void
  selectActivity: (bpmnElementId: string | null) => void
  invalidateResults: () => void
  reset: () => void
  loadLatestForProcess: (processId: string) => Promise<void>
}

export const useSimulationStore = create<SimulationState>((set) => ({
  resultActual: null,
  resultAutomated: null,
  lastSimulatedAt: null,
  lastPersistedExecutedAt: null,
  isRunning: false,
  error: null,
  selectedActivityId: null,

  persistResults: async (processId, actual, automated) => {
    const executedAt = Date.now()
    await supabaseSimulationRepo.save({
      id: uuidv4(),
      processId,
      executedAt,
      result: actual,
      resultAutomated: automated,
    })
    set({
      resultActual: actual,
      resultAutomated: automated,
      lastSimulatedAt: new Date(),
      lastPersistedExecutedAt: executedAt,
      error: null,
    })
  },

  setRunning: (isRunning) => set({ isRunning }),
  setError: (error) => set({ error }),
  selectActivity: (selectedActivityId) => set({ selectedActivityId }),

  invalidateResults: () =>
    set({ resultActual: null, resultAutomated: null, lastSimulatedAt: null }),

  reset: () =>
    set({
      resultActual: null,
      resultAutomated: null,
      lastSimulatedAt: null,
      lastPersistedExecutedAt: null,
      isRunning: false,
      error: null,
      selectedActivityId: null,
    }),

  loadLatestForProcess: async (processId) => {
    const sim = await supabaseSimulationRepo.getLatestByProcess(processId)
    set({ lastPersistedExecutedAt: sim?.executedAt ?? null })
  },
}))

// Suscripción reactiva: cualquier cambio en activities o currentProcess del process-store
// invalida los resultados para garantizar que nunca haya resultados "viejos" visibles.
useProcessStore.subscribe((state, prevState) => {
  if (
    state.activities !== prevState.activities ||
    state.currentProcess !== prevState.currentProcess
  ) {
    useSimulationStore.getState().invalidateResults()
  }
})
