import type { ParamFieldDef } from '@/types/workflow'

/** 动作类型选项 */
export const ACTION_TYPE_OPTIONS = [
  { label: '取货', value: 'fetch' },
  { label: '放货', value: 'put' }
] as const

/** 执行动作：对齐 VDA5050 Order.actions[] 单条 Action 结构（不含 actionId，下发时由运行时生成） */
export function executeActionParams(): ParamFieldDef[] {
  return [
    {
      key: 'actionType',
      label: '动作类型',
      type: 'select',
      required: true,
      defaultValue: 'fetch',
      options: [...ACTION_TYPE_OPTIONS]
    },
    {
      key: 'actionParameters',
      label: '动作参数 (actionParameters)',
      type: 'textarea',
      placeholder: 'JSON 数组：[{"key":"height","value":"100"}]'
    }
  ]
}

/** 导出/下发前解析为 VDA5050 Action 对象 */
export function resolveVda5050Action(params: Record<string, unknown>): {
  actionType: string
  actionParameters: Array<{ key: string; value: string }>
} {
  let actionParameters: Array<{ key: string; value: string }> = []
  const raw = params.actionParameters
  if (typeof raw === 'string' && raw.trim()) {
    try {
      const parsed = JSON.parse(raw) as unknown
      if (Array.isArray(parsed)) {
        actionParameters = parsed.map((item) => {
          const row = item as Record<string, unknown>
          return { key: String(row.key ?? ''), value: String(row.value ?? '') }
        })
      }
    } catch {
      /* 静态页阶段由用户自行保证 JSON 合法 */
    }
  }

  return {
    actionType: String(params.actionType ?? ''),
    actionParameters
  }
}
