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

export const MatchesAssertionKind = 'HttpAction#MatchesAssertion'

/**
 * An assertion that makes sure the input value matches a regexp.
 */
export interface IMatchesAssertion extends IHttpStep {
  kind: typeof MatchesAssertionKind

  /**
   * The regexp to match the value against.
   */
  value?: string
}

/**
 * An assertion that makes sure the input value matches a regexp.
 */
export class MatchesAssertion extends HttpStep {
  override kind = MatchesAssertionKind

  /**
   * The regexp to match the value against.
   */
  value?: string

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

  override new(init: IMatchesAssertion): void {
    super.new(init)
    this.kind = MatchesAssertionKind
    this.value = init.value
  }

  checkValidity(): boolean {
    return !!this.value
  }

  override toJSON(): IMatchesAssertion {
    const result: IMatchesAssertion = {
      ...super.toJSON(),
      kind: MatchesAssertionKind,
    }
    if (this.value) {
      result.value = this.value
    }
    return result
  }
}
