import type { components } from '../api/generated/schema'
import {
  normalizeOperationResult,
  type OperationResultDto,
} from '../api/contracts'
import { useMissionControlUiStore } from '../stores/missionControlUi'

type GeneratedOperationResult = components['schemas']['OperationResultDto']

export function reportOperationResult(
  value: GeneratedOperationResult | OperationResultDto | null | undefined,
  title = 'Operation',
): OperationResultDto | null {
  const result = normalizeOperationResult(value as GeneratedOperationResult | null | undefined)
  if (result) useMissionControlUiStore().showOperation(result, title)
  return result
}

export function reportOperationEnvelope(
  value: unknown,
  title = 'Operation',
): OperationResultDto | null {
  if (!value || typeof value !== 'object' || !('operation' in value)) return null
  const operation = (value as { operation?: unknown }).operation
  if (!operation || typeof operation !== 'object') return null
  const candidate = operation as Partial<GeneratedOperationResult>
  if (
    typeof candidate.operationId !== 'string'
    || typeof candidate.status !== 'string'
    || !Array.isArray(candidate.affectedRefs)
  ) return null
  return reportOperationResult(candidate as GeneratedOperationResult, title)
}
