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

export const GreaterThanAssertionKind = 'HttpAction#GreaterThanAssertion'

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

  /**
   * 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 greater [or equal] to the set value.
 */
export class GreaterThanAssertion extends HttpStep {
  override kind = GreaterThanAssertionKind

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

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

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

  override new(init: IGreaterThanAssertion): void {
    super.new(init)
    this.kind = GreaterThanAssertionKind
    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(): IGreaterThanAssertion {
    const result: IGreaterThanAssertion = {
      ...super.toJSON(),
      kind: GreaterThanAssertionKind,
    }
    if (typeof this.value === 'number') {
      result.value = this.value
    }
    if (typeof this.equal === 'boolean') {
      result.equal = this.equal
    }
    return result
  }
}
