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

export const ReadDataSourceStepKind = 'HttpAction#ReadDataSource'

/**
 * A step similar to `ReadDataStep` but it does not search for a value by the path
 * but returns the whole part of the request / response data (like status code,
 * status message, response headers, response body, request body, etc)
 */
export interface IReadDataSourceStep extends IHttpStep {
  /**
   * The source of the data.
   */
  source?: FlowSourceEnum

  /**
   * The data to read.
   */
  data?: FlowRequestDataEnum | FlowResponseDataEnum
}

/**
 * A step similar to `ReadDataStep` but it does not search for a value by the path
 * but returns the whole part of the request / response data (like status code,
 * status message, response headers, response body, request body, etc)
 */
export class ReadDataSourceStep extends HttpStep {
  override kind = ReadDataSourceStepKind

  /**
   * The source of the data.
   */
  source?: FlowSourceEnum

  /**
   * The data to read.
   */
  data?: FlowRequestDataEnum | FlowResponseDataEnum

  /**
   * Creates the step from values.
   * @param source The main data source.
   * @param path The path to the data.
   * @param data Source of the data in the `source`. This is optional for non-http-request source.
   */
  constructor(source: FlowSourceEnum, data: FlowRequestDataEnum | FlowResponseDataEnum)

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

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

  constructor(sourceOrInit?: FlowSourceEnum | IReadDataSourceStep, data?: FlowRequestDataEnum | FlowResponseDataEnum) {
    super()
    if (!sourceOrInit) {
      return
    }
    if (typeof sourceOrInit === 'object') {
      const typed = sourceOrInit as IReadDataSourceStep
      this.new(typed)
    } else if (typeof sourceOrInit === 'string') {
      this.new({
        kind: ReadDataSourceStepKind,
        source: sourceOrInit,
        data,
        enabled: true,
      })
    }
  }

  override new(init: IReadDataSourceStep): void {
    super.new(init)
    this.kind = ReadDataSourceStepKind
    this.source = init.source
    this.data = init.data
  }

  checkValidity(): boolean {
    const { source, data } = this
    return !!source && !!data
  }

  override toJSON(): IReadDataSourceStep {
    const result: IReadDataSourceStep = {
      ...super.toJSON(),
      kind: ReadDataSourceStepKind,
    }
    if (this.source) {
      result.source = this.source
    }
    if (this.data) {
      result.data = this.data
    }
    return result
  }
}
