import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { redBlueSchema, type RedBlueInput } from '@/lib/api/schemas'
import { listRedBlueRuns, listStressScenarios, runRedBlue } from '@/lib/services/red-blue-service'

export const dynamic = 'force-dynamic'

/** The stress library and past exchanges (§24, §26). */
export const GET = apiRoute({ permission: 'resilience.run' }, async ({ searchParams }) => {
  const limit = Math.min(30, Math.max(1, Number(searchParams.get('limit')) || 10))
  const runs = await listRedBlueRuns(limit)

  return {
    scenarios: listStressScenarios(),
    runs: runs.map((run) => ({
      code: run.code,
      stressKind: run.stressKind,
      title: run.title,
      titleAr: run.titleAr,
      resilienceBefore: run.resilienceBefore,
      resilienceDuring: run.resilienceDuring,
      riskBefore: run.riskBefore,
      riskDuring: run.riskDuring,
      weakestFactor: run.weakestFactor,
      narrative: run.narrative,
      narrativeAr: run.narrativeAr,
      createdAt: run.createdAt.getTime(),
      responses: run.responses.map((response) => ({
        code: response.code,
        strategyLabel: response.strategyLabel,
        strategyLabelAr: response.strategyLabelAr,
        resilienceAfter: response.resilienceAfter,
        riskAfter: response.riskAfter,
        recoveryMin: response.recoveryMin,
        costIndex: response.costIndex,
        customersImpacted: response.customersImpacted,
        isRecommended: response.isRecommended,
        rank: response.rank,
        actions: response.actions.map((action) => ({
          actionKey: action.actionKey,
          assetCode: action.assetCode,
          magnitudeMw: action.magnitudeMw,
        })),
      })),
    })),
  }
})

/** Run a stress and search for the best response to it (§25, §26). */
export const POST = apiRoute<Record<string, string>, RedBlueInput>(
  { permission: 'resilience.run', bodySchema: redBlueSchema, limit: 12 },
  async ({ body, user, request }) => {
    const outcome = await runRedBlue({
      stressKind: body.stressKind,
      regionCode: body.regionCode ?? null,
      assetCode: body.assetCode ?? null,
      twinCode: body.twinCode ?? null,
      persist: body.persist ?? true,
      userId: user.id,
    })
    if (!outcome) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.redBlueRun,
      entity: 'resilience',
      entityId: outcome.code,
      user,
      request,
      detail: outcome.narrative,
    })

    return outcome
  },
)
