"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var ServerNodeFailsafeContext_exports = {};
__export(ServerNodeFailsafeContext_exports, {
  ServerNodeFailsafeContext: () => ServerNodeFailsafeContext
});
module.exports = __toCommonJS(ServerNodeFailsafeContext_exports);
var import_network_commissioning = require("#behaviors/network-commissioning");
var import_general = require("@matter/general");
var import_protocol = require("@matter/protocol");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
class ServerNodeFailsafeContext extends import_protocol.FailsafeContext {
  #node;
  #storedState;
  constructor(node, options) {
    super(options);
    this.#node = node;
    this.#node.env.set(import_protocol.FailsafeContext, this);
    this.construction.change.on((status) => {
      if (status === import_general.Lifecycle.Status.Destroyed) {
        this.#node.env.delete(import_protocol.FailsafeContext, this);
      }
    });
  }
  /**
   * Persist endpoint credentials and network configurations for restoration if commissioning does not complete.
   *
   * The Matter 1.2 specification makes it pretty clear that Matter supports configuration of multiple network
   * interfaces (e.g. @see {@link MatterSpecification.v11.Core} § 11.8.8 and § 2.3.2).
   * {@link NetworkCommissioningCluster} of the primary interface is on the root endpoint.  However it's not clear
   * where {@link NetworkCommissioningCluster} instances for secondary interfaces reside.  To be on the safe side
   * we just assume any endpoint may support {@link NetworkCommissioningCluster}.
   *
   * TODO - it's recommended to reset all state if commissioning bails; currently we perform mandatory restore
   */
  async storeEndpointState() {
    this.#storedState = {
      networks: /* @__PURE__ */ new Map()
    };
    if (!this.#node.behaviors.has(import_network_commissioning.NetworkCommissioningBehavior)) {
      return;
    }
    this.#node.visit((endpoint) => {
      if (endpoint.behaviors.has(import_network_commissioning.NetworkCommissioningBehavior)) {
        this.#storedState?.networks.set(endpoint, endpoint.stateOf(import_network_commissioning.NetworkCommissioningBehavior).networks);
      }
    });
  }
  async restoreNetworkState() {
    await this.#node.act(this.restoreNetworkState.name, async (agent) => {
      const context = agent.context;
      await this.#node.visit(async (endpoint) => {
        const networks = this.#storedState?.networks.get(endpoint);
        if (networks) {
          endpoint.agentFor(context).get(import_network_commissioning.NetworkCommissioningBehavior).state.networks = [...networks];
        }
      });
    });
  }
  async restoreBreadcrumb() {
    await this.#node.act(this.restoreBreadcrumb.name, async (agent) => {
      const tx = agent.context.transaction;
      await tx.addResources(agent.generalCommissioning);
      await tx.begin();
      agent.generalCommissioning.state.breadcrumb = 0;
    });
  }
  async rollback(currentExchange) {
    if (!this.fabricIndex && this.hasRootCert) {
      try {
        const fabricManager = this.#node.env.get(import_protocol.FabricManager);
        fabricManager.events.failsafeClosed.emit();
      } catch (error) {
        import_general.UnsupportedDependencyError.accept(error);
      }
    }
    return super.rollback(currentExchange);
  }
  /*
      override async restoreFabric() {
          await super.restoreFabric();
          await this.#restoreOperationalCredentials();
      }
  
      async #restoreOperationalCredentials() {
          if (this.#operationalCredentialsRestored) {
              return;
          }
  
          const state = this.#storedState;
          if (state) {
              await this.#node.act(agent => {
                  const opcreds = agent.operationalCredentials.state;
                  opcreds.nocs = state.nocs;
                  opcreds.fabrics = state.fabrics;
                  opcreds.commissionedFabrics = opcreds.fabrics.length;
                  opcreds.trustedRootCertificates = state.trustedRootCertificates;
              });
          }
  
          this.#operationalCredentialsRestored = true;
      }
      */
}
//# sourceMappingURL=ServerNodeFailsafeContext.js.map
