// KueSync Companion module — upgrade scripts (button compatibility across versions)
// © 2026 Krometis Analytics. All rights reserved.
//
// COMPATIBILITY POLICY: buttons an operator built on ANY older KueSync module version must keep
// working after an upgrade, untouched. Concretely:
//   • action / feedback / variable IDs are NEVER renamed or removed — only added,
//   • option fields are NEVER renamed — only added, and every callback tolerates a missing option
//     (defaults applied with `||` / `??` in actions.js / feedbacks.js),
//   • config fields are NEVER renamed — only added with safe defaults.
// These scripts run once per connection when Companion loads a config saved by an older version,
// backfilling defaults for fields that didn't exist yet so old buttons are indistinguishable from
// freshly-made ones. Add a new script for every release that introduces fields — never edit old ones.

// v6.x line: next/prev gained `mode` + `machines`; goto/jump gained `machines`; config gained
// `prefSubnet` (preferred network) and the cue-light fields `cueMode` / `cueHoldMs`.
function v6AddedFieldDefaults(_context, props) {
  const result = { updatedConfig: null, updatedActions: [], updatedFeedbacks: [] }

  for (const action of props.actions || []) {
    let changed = false
    const opts = action.options || (action.options = {})
    if (action.actionId === 'next' || action.actionId === 'prev') {
      if (opts.mode === undefined) { opts.mode = 'relative'; changed = true }
      if (opts.machines === undefined) { opts.machines = ''; changed = true }
    }
    if (action.actionId === 'goto' || action.actionId === 'jump') {
      if (opts.machines === undefined) { opts.machines = ''; changed = true }
    }
    if (changed) result.updatedActions.push(action)
  }

  if (props.config) {
    const c = props.config
    let changed = false
    if (c.prefSubnet === undefined) { c.prefSubnet = ''; changed = true }
    if (c.cueMode === undefined) { c.cueMode = 'flash'; changed = true }
    if (c.cueHoldMs === undefined) { c.cueHoldMs = 900; changed = true }
    if (changed) result.updatedConfig = c
  }

  return result
}

// v6.2.6: config gained `syncMode` (the previously-dead branch is now a real dropdown). Existing
// configs get 'tod' — exactly the behavior they already had.
function v626SyncMode(_context, props) {
  const result = { updatedConfig: null, updatedActions: [], updatedFeedbacks: [] }
  if (props.config && props.config.syncMode === undefined) {
    props.config.syncMode = 'tod'
    result.updatedConfig = props.config
  }
  return result
}

export const UpgradeScripts = [v6AddedFieldDefaults, v626SyncMode]
export default UpgradeScripts
