import { HttpStep, IHttpStep } from '../../HttpStep.js'

export const LessThanAssertionKind = 'HttpAction#LessThanAssertion'

/**
 * An assertion that makes sure the input value is less [or equal] to the set value.
 */
export interface ILessThanAssertion extends IHttpStep {
  kind: typeof LessThanAssertionKind

  /**
   * The value to compare to.
   */
  value?: number

  /**
   * When set it treats the assertion as "greater than or equal"
   */
  equal?: boolean
}

/**
 * An assertion that makes sure the input value is less [or equal] to the set value.
 */
export class LessThanAssertion extends HttpStep {
  override kind = LessThanAssertionKind

  /**
   * The value to compare to.
   */
  value?: number

  /**
   * When set it treats the assertion as "greater than or equal"
   */
  equal?: boolean

  constructor(valueOrInit?: ILessThanAssertion | number, equal?: boolean) {
    super()
    if (typeof valueOrInit === 'object') {
      const typed = valueOrInit as ILessThanAssertion
      this.new(typed)
    } else if (typeof valueOrInit === 'number') {
      this.new({
        kind: LessThanAssertionKind,
        value: valueOrInit,
        equal,
        enabled: true,
      })
    }
  }

  override new(init: ILessThanAssertion): void {
    super.new(init)
    this.kind = LessThanAssertionKind
    this.value = init.value
    if (typeof init.equal === 'boolean') {
      this.equal = init.equal
    } else {
      this.equal = undefined
    }
  }

  checkValidity(): boolean {
    return typeof this.value === 'number'
  }

  override toJSON(): ILessThanAssertion {
    const result: ILessThanAssertion = {
      ...super.toJSON(),
      kind: LessThanAssertionKind,
    }
    if (this.value) {
      result.value = this.value
    }
    if (typeof this.equal === 'boolean') {
      result.equal = this.equal
    }
    return result
  }
}
