import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { liveGridTraceSchema, type LiveGridTraceInput } from '@/lib/api/schemas'
import { traceAsset } from '@/lib/services/live-grid-service'

export const dynamic = 'force-dynamic'

/**
 * Trace the power to a load, or the loads from an asset (§54, §55).
 *
 * Follows the solved flow rather than the declared topology, so a path that has reversed
 * is traced the way power is actually moving.
 */
export const POST = apiRoute<Record<string, string>, LiveGridTraceInput>(
  { permission: 'twin.read', bodySchema: liveGridTraceSchema, limit: 90 },
  async ({ body, user, request }) => {
    const trace = await traceAsset(body.assetCode, body.direction, {
      twinCode: body.twinCode,
      scenario: body.scenario ?? null,
    })
    if (!trace) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.liveGridTraced,
      entity: 'asset',
      entityId: body.assetCode,
      user,
      request,
      detail: `${body.direction}: ${trace.path.length} hops`,
    })

    return trace
  },
)
