import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { getWarRoom } from '@/lib/services/warroom-service'
import { intelligenceDto } from '@/lib/services/intelligence-dto'

export const dynamic = 'force-dynamic'

/** The war room's state for one asset, or for whichever asset needs it most (§21–§23). */
export const GET = apiRoute({ permission: 'warroom.access', limit: 60 }, async ({ searchParams }) => {
  const assetCode = searchParams.get('assetCode')?.trim() || undefined
  const state = await getWarRoom({ assetCode })
  if (!state) throw new ApiError(ERROR_CODES.notFound)

  return {
    active: state.active,
    threshold: state.threshold,
    secondsToEvent: state.secondsToEvent,
    isEstimated: state.isEstimated,
    branches: state.branches,
    patterns: state.patterns,
    decisions: state.decisions,
    intelligence: intelligenceDto(state.intel),
  }
})
