import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { optimizationSchema, type OptimizationInput } from '@/lib/api/schemas'
import { toPerturbation } from '@/lib/api/overlay'
import { runSelfHealing } from '@/lib/services/optimization-service'
import { strategyDto } from '@/lib/services/intelligence-dto'
import { OBJECTIVE_PRESETS } from '@/lib/engine/optimize'

export const dynamic = 'force-dynamic'

/**
 * The Self-Healing Lab (§12).
 *
 * Generates candidate recovery strategies, simulates each one and returns them side by
 * side with the objective terms that separated them. Nothing is executed: the response
 * is a comparison for a human to choose from (§13, §43).
 */
export const POST = apiRoute<Record<string, string>, OptimizationInput>(
  { permission: 'optimization.run', bodySchema: optimizationSchema, limit: 30 },
  async ({ body }) => {
    const result = await runSelfHealing(body.assetCode, {
      perturbation: toPerturbation(body.overlay),
      objectiveKey: body.objectiveKey,
    })
    if (!result) throw new ApiError(ERROR_CODES.notFound)

    return {
      assetCode: result.assetCode,
      objectiveKey: result.objectiveKey,
      objectiveWeights: OBJECTIVE_PRESETS[result.objectiveKey] ?? OBJECTIVE_PRESETS.balanced,
      riskBefore: result.riskBefore,
      horizonMin: result.horizonMin,
      strategies: result.strategies.map(strategyDto),
      best: result.best ? strategyDto(result.best) : null,
      executionIsSimulated: true,
    }
  },
)
