/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { camelize, decamelize, ImplementationError, NotImplementedError } from "#general";
import { ApiResource } from "../ApiResource.js";
import { Envelope } from "../Envelope.js";
class CommandResource extends ApiResource {
  #behavior;
  supervisor;
  isInvocable = true;
  constructor(parent, behavior, schema) {
    super(parent);
    this.#behavior = behavior;
    this.supervisor = this.supervisorFor(schema);
  }
  get schema() {
    return this.supervisor.schema;
  }
  get id() {
    return decamelize(this.schema.name);
  }
  get dataModelPath() {
    return this.parent.dataModelPath.at(this.id);
  }
  get valueKind() {
    return "command";
  }
  get value() {
    return void 0;
  }
  async invoke(request) {
    let input = new Envelope({ supervisor: this.supervisor, ...request });
    if (input.js === void 0 || input.js === null) {
      input = new Envelope({ supervisor: this.supervisor, js: {} });
    }
    const name = camelize(this.id);
    const method = this.#behavior[name];
    if (typeof method !== "function") {
      throw new NotImplementedError();
    }
    input.validate();
    const result = await method.call(this.#behavior, input.js);
    const responseSchema = this.schema.responseModel;
    if (!responseSchema) {
      return;
    }
    const output = new Envelope({ supervisor: this.supervisorFor(responseSchema), js: result });
    try {
      output.validate();
    } catch (e) {
      const error = new ImplementationError("Command output validation failed");
      error.cause = e;
      throw error;
    }
    return output;
  }
}
export {
  CommandResource
};
//# sourceMappingURL=CommandResource.js.map
