import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { decisionCreateSchema, type DecisionCreateInput } from '@/lib/api/schemas'
import { createDecision, listDecisions, storedConfidence } from '@/lib/services/decision-service'

export const dynamic = 'force-dynamic'

/** The decision audit trail (§41). */
export const GET = apiRoute({ permission: 'decisions.read' }, async ({ searchParams }) => {
  const limit = Math.min(50, Math.max(1, Number(searchParams.get('limit')) || 25))
  const status = searchParams.get('status')?.trim() || undefined
  const records = await listDecisions({ limit, status })

  return {
    decisions: records.map((record) => ({
      code: record.code,
      assetCode: record.assetCode,
      title: record.title,
      titleAr: record.titleAr,
      rationale: record.rationale,
      rationaleAr: record.rationaleAr,
      status: record.status,
      riskBefore: record.riskBefore,
      riskAfter: record.riskAfter,
      confidence: storedConfidence(record),
      dataTs: record.dataTs.getTime(),
      createdAt: record.createdAt.getTime(),
      outcome: record.outcome,
      outcomeAr: record.outcomeAr,
      approvals: record.approvals.map((approval) => ({
        step: approval.step,
        decision: approval.decision,
        userName: approval.userName,
        userNameAr: approval.userNameAr,
        comment: approval.comment,
        commentAr: approval.commentAr,
        decidedAt: approval.decidedAt?.getTime() ?? null,
      })),
      strategy: record.strategy
        ? {
            code: record.strategy.code,
            label: record.strategy.label,
            labelAr: record.strategy.labelAr,
            actions: record.strategy.actions.map((action) => ({
              actionType: action.actionType,
              magnitudeMw: action.magnitudeMw,
              label: action.label,
              labelAr: action.labelAr,
            })),
          }
        : null,
    })),
  }
})

/**
 * Raise a decision for review (§13).
 *
 * Creating one does not approve anything: the record is born pending, with an operator
 * step and a supervisor step waiting for named humans.
 */
export const POST = apiRoute<Record<string, string>, DecisionCreateInput>(
  { permission: 'decisions.approve', bodySchema: decisionCreateSchema, limit: 30 },
  async ({ body, user, request }) => {
    const code = await createDecision({
      assetCode: body.assetCode,
      strategyCode: body.strategyCode ?? null,
      orchestrationId: body.orchestrationId ?? null,
      userId: user.id,
    })
    if (!code) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.decisionCreated,
      entity: 'decision',
      entityId: code,
      user,
      request,
      detail: `Raised for ${body.assetCode}, awaiting operator and supervisor approval`,
    })

    return { code, status: 'pending' }
  },
)
