import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { stressTestSchema, type StressTestInput } from '@/lib/api/schemas'
import { runStressTest } from '@/lib/services/stress-service'

export const dynamic = 'force-dynamic'

/**
 * Grid stress test (§29).
 *
 * Each step rebuilds the entire national twin, so the request is bounded by the schema
 * and rate limited: this is the most expensive read in the platform.
 */
export const POST = apiRoute<Record<string, string>, StressTestInput>(
  { permission: 'stress.run', bodySchema: stressTestSchema, limit: 12 },
  async ({ body, user, request }) => {
    const result = await runStressTest({
      regionCode: body.regionCode ?? null,
      maxDeltaPct: body.maxDeltaPct,
      stepPct: body.stepPct,
    })

    await writeAudit({
      action: AUDIT_ACTIONS.stressTestRun,
      entity: 'grid',
      entityId: body.regionCode ?? 'national',
      user,
      request,
      detail:
        result.breakingPointPct === null
          ? `No limit exceeded up to +${result.headroomPct} % demand`
          : `First limit exceeded at +${result.breakingPointPct} % on ${result.weakestAssetCode}`,
    })

    return result
  },
)
