import { useCallback } from 'react'
import { useProcessStore } from '@/store/process-store'
import { useSimulationStore } from '@/store/simulation-store'
import { runSimulation } from '@/domain/simulation'
import type { SimulationInput } from '@/domain/types'

export function useSimulate() {
  const { currentProcess, activities, gateways, resources } = useProcessStore()
  const { persistResults, setRunning, setError } = useSimulationStore()

  const simulate = useCallback(async () => {
    if (!currentProcess) {
      setError('No hay proceso cargado')
      return null
    }

    setRunning(true)
    setError(null)

    try {
      const baseInput: Omit<SimulationInput, 'scenario'> = {
        processXml: currentProcess.bpmnXml,
        activities: new Map(activities.map((a) => [a.bpmnElementId, a])),
        gateways: new Map(gateways.map((g) => [g.bpmnElementId, g])),
        resources: new Map(resources.map((r) => [r.id, r])),
        globalSettings: {
          currency: currentProcess.currency,
          overheadPercentage: currentProcess.overheadPercentage,
        },
      }

      // Las dos simulaciones se computan y persisten SIEMPRE en conjunto (regla dura).
      const resultActual = runSimulation({ ...baseInput, scenario: 'actual' })
      const resultAutomated = runSimulation({ ...baseInput, scenario: 'automated' })

      await persistResults(currentProcess.id, resultActual, resultAutomated)
      setRunning(false)
      return { resultActual, resultAutomated }
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Error en la simulación'
      setError(message)
      setRunning(false)
      return null
    }
  }, [currentProcess, activities, gateways, resources, persistResults, setRunning, setError])

  return { simulate }
}
