import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { counterfactualSchema, type CounterfactualRequest } from '@/lib/api/schemas'
import { toPerturbation } from '@/lib/api/overlay'
import { runCounterfactual } from '@/lib/services/counterfactual-service'
import { getTwinRecord } from '@/lib/services/twin-service'

export const dynamic = 'force-dynamic'

/** The minimum-intervention search, run against a twin member (§43). */
export const POST = apiRoute<{ code: string }, CounterfactualRequest>(
  { permission: 'counterfactual.run', bodySchema: counterfactualSchema, limit: 20 },
  async ({ params, body }) => {
    const twin = await getTwinRecord(params.code)
    if (!twin) throw new ApiError(ERROR_CODES.notFound)

    const outcome = await runCounterfactual({
      assetCode: body.assetCode,
      objective: body.objective,
      targetValue: body.targetValue,
      perturbation: toPerturbation(body.overlay),
    })
    if (!outcome) throw new ApiError(ERROR_CODES.notFound)

    return { twinCode: twin.code, source: 'simulated', ...outcome }
  },
)
