import { RateLimitRule, type RateLimitRuleSchema } from './RateLimitRule.js'
import { observed } from '../../decorators/observed.js'

/**
 * Defines the rate limiting and throttling policies for the entire API.
 */
export interface RateLimitingConfigurationSchema {
  /**
   * An ordered list of rules. The first rule that matches an incoming
   * request will be applied.
   */
  rules: RateLimitRuleSchema[]
}

export class RateLimitingConfiguration extends EventTarget implements RateLimitingConfigurationSchema {
  @observed({ deep: true }) accessor rules: RateLimitRule[]

  constructor(state: Partial<RateLimitingConfigurationSchema> = {}) {
    super()
    this.rules = state.rules?.map((rule) => new RateLimitRule(rule)) || []
  }

  toJSON(): RateLimitingConfigurationSchema {
    return {
      rules: this.rules.map((rule) => rule.toJSON()),
    }
  }

  notifyChange() {
    this.dispatchEvent(new Event('change'))
  }
}
