/* eslint-disable @typescript-eslint/unified-signatures */
import { HttpStep, IHttpStep } from '../../HttpStep.js'

export const SetVariableStepKind = 'HttpAction#SetVariable'

/**
 * A step that accepts an input from the previous step and sets a variable in the current environment
 * with this value. If the value is `void`, `null`, or `undefined` then the variable is removed from the
 * environment.
 *
 * All variables are strings.
 */
export interface ISetVariableStep extends IHttpStep {
  kind: typeof SetVariableStepKind
  /**
   * The name of the variable to set
   */
  name: string
}

export class SetVariableStep extends HttpStep {
  override kind = SetVariableStepKind

  /**
   * The name of the variable to set
   */
  name = ''

  /**
   * Creates the step from values.
   * @param name The name of the variable to set
   */
  constructor(name: string)

  /**
   * Creates the step from serialized schema.
   * @param init The serialized step values.
   */
  constructor(init: ISetVariableStep)

  /**
   * Creates an empty step.
   */
  constructor()

  constructor(nameOrInit?: string | ISetVariableStep) {
    super()
    if (!nameOrInit) {
      return
    }
    if (typeof nameOrInit === 'object') {
      const typed = nameOrInit as ISetVariableStep
      this.new(typed)
    } else if (typeof nameOrInit === 'string') {
      this.new({
        kind: SetVariableStepKind,
        name: nameOrInit,
        enabled: true,
      })
    }
  }

  override new(init: ISetVariableStep): void {
    super.new(init)
    this.kind = SetVariableStepKind
    this.name = init.name
  }

  checkValidity(): boolean {
    const { name } = this
    return !!name
  }

  override toJSON(): ISetVariableStep {
    const result: ISetVariableStep = {
      ...super.toJSON(),
      kind: SetVariableStepKind,
      name: this.name,
    }
    return result
  }
}
