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

export const LengthOfAssertionKind = 'HttpAction#LengthOfAssertion'

/**
 * An assertion that makes sure the input has a length of the specified value.
 */
export interface ILengthOfAssertion extends IHttpStep {
  kind: typeof LengthOfAssertionKind

  /**
   * The expected size of the array.
   */
  value?: number
}

/**
 * An assertion that makes sure the input has a length of the specified value.
 */
export class LengthOfAssertion extends HttpStep {
  override kind = LengthOfAssertionKind

  /**
   * The expected size of the array.
   */
  value?: number

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

  override new(init: ILengthOfAssertion): void {
    super.new(init)
    this.kind = LengthOfAssertionKind
    this.value = init.value
  }

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

  override toJSON(): ILengthOfAssertion {
    const result: ILengthOfAssertion = {
      ...super.toJSON(),
      kind: LengthOfAssertionKind,
    }
    if (typeof this.value === 'number') {
      result.value = this.value
    }
    return result
  }
}
