import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { paretoSchema, type ParetoInput } from '@/lib/api/schemas'
import { toPerturbation } from '@/lib/api/overlay'
import { exploreStrategies } from '@/lib/services/pareto-service'

export const dynamic = 'force-dynamic'

/**
 * The non-dominated strategy set, with a reason for every option that is not the
 * recommendation (§35, §37).
 */
export const POST = apiRoute<Record<string, string>, ParetoInput>(
  { permission: 'optimization.run', bodySchema: paretoSchema, limit: 30 },
  async ({ body, user, request }) => {
    const view = await exploreStrategies({
      assetCode: body.assetCode,
      perturbation: toPerturbation(body.overlay),
      persist: body.persist,
    })
    if (!view) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.paretoExplored,
      entity: 'asset',
      entityId: body.assetCode,
      user,
      request,
      detail: `${view.result.frontier.length} on the frontier, ${view.rejectedByPhysics} rejected by physics`,
    })

    return view
  },
)
