"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 GeneralCommissioningServer_exports = {};
__export(GeneralCommissioningServer_exports, {
  GeneralCommissioningServer: () => GeneralCommissioningServer
});
module.exports = __toCommonJS(GeneralCommissioningServer_exports);
var import_administrator_commissioning = require("#behaviors/administrator-commissioning");
var import_basic_information = require("#behaviors/basic-information");
var import_general = require("@matter/general");
var import_protocol = require("@matter/protocol");
var import_administrator_commissioning2 = require("@matter/types/clusters/administrator-commissioning");
var import_general_commissioning = require("@matter/types/clusters/general-commissioning");
var import_GeneralCommissioningBehavior = require("./GeneralCommissioningBehavior.js");
var import_ServerNodeFailsafeContext = require("./ServerNodeFailsafeContext.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const SuccessResponse = { errorCode: import_general_commissioning.GeneralCommissioning.CommissioningError.Ok, debugText: "" };
const logger = import_general.Logger.get("GeneralCommissioningClusterHandler");
class GeneralCommissioningServer extends import_GeneralCommissioningBehavior.GeneralCommissioningBehavior {
  static lockOnInvoke = false;
  initialize() {
    const bci = this.state.basicCommissioningInfo;
    if (bci.failSafeExpiryLengthSeconds === void 0) {
      bci.failSafeExpiryLengthSeconds = 60;
    }
    if (bci.maxCumulativeFailsafeSeconds === void 0) {
      bci.maxCumulativeFailsafeSeconds = 900;
    }
    this.state.breadcrumb = 0;
    const sessionManager = this.env.get(import_protocol.SessionManager);
    this.reactTo(sessionManager.sessions.added, this.#handleAddedPaseSessions);
  }
  /** As required by Commissioning Flows any new PASE session needs to arm the failsafe for 60s. */
  async #handleAddedPaseSessions(session) {
    if (session.isInitiator || // Only server sessions
    !session.isPase || // Only PASE sessions
    session.fabric !== void 0) {
      return;
    }
    logger.debug(session.via, `New PASE session, arming failsafe for 60s`);
    await this.#armFailSafe({ breadcrumb: this.state.breadcrumb, expiryLengthSeconds: 60 }, session);
  }
  async #armFailSafe({ breadcrumb, expiryLengthSeconds }, session) {
    import_protocol.NodeSession.assert(session, "Failsafe may only be armed on a secure session");
    const commissioner = this.env.get(import_protocol.DeviceCommissioner);
    try {
      if (!commissioner.isFailsafeArmed && this.agent.get(import_administrator_commissioning.AdministratorCommissioningServer).state.windowStatus !== import_administrator_commissioning2.AdministratorCommissioning.CommissioningWindowStatus.WindowNotOpen && !session.isPase) {
        throw new import_general.MatterFlowError("Cannot arm failsafe using CASE while commissioning window is opened");
      }
      if (commissioner.isFailsafeArmed) {
        await commissioner.failsafeContext.extend(
          session.fabric,
          (0, import_general.Seconds)(expiryLengthSeconds),
          this.context.exchange
        );
      } else {
        if (expiryLengthSeconds === 0) return SuccessResponse;
        const failsafe = new import_ServerNodeFailsafeContext.ServerNodeFailsafeContext(this.endpoint, {
          fabrics: this.env.get(import_protocol.FabricManager),
          sessions: this.env.get(import_protocol.SessionManager),
          expiryLength: (0, import_general.Seconds)(expiryLengthSeconds),
          maxCumulativeFailsafe: (0, import_general.Seconds)(this.state.basicCommissioningInfo.maxCumulativeFailsafeSeconds),
          session
        });
        commissioner.beginTimed(failsafe);
        await failsafe.construction;
      }
      if (commissioner.isFailsafeArmed) {
        this.state.breadcrumb = breadcrumb;
      }
    } catch (error) {
      import_general.MatterFlowError.accept(error);
      logger.debug(`Error while arming failSafe timer:`, error);
      return {
        errorCode: import_general_commissioning.GeneralCommissioning.CommissioningError.BusyWithOtherAdmin,
        debugText: error.message
      };
    }
    return SuccessResponse;
  }
  armFailSafe(request) {
    (0, import_protocol.assertRemoteActor)(this.context);
    return this.#armFailSafe(request, this.context.session);
  }
  async setRegulatoryConfig({
    breadcrumb,
    newRegulatoryConfig,
    countryCode
  }) {
    const locationCapabilityValue = this.state.locationCapability;
    const basicInformation = this.agent.get(import_basic_information.BasicInformationServer);
    const currentLocationCountryCode = basicInformation.state.location;
    if (currentLocationCountryCode !== countryCode) {
      if (this.state.allowCountryCodeChange === false && countryCode !== "XX") {
        return {
          errorCode: import_general_commissioning.GeneralCommissioning.CommissioningError.ValueOutsideRange,
          debugText: `Country code change not allowed: ${countryCode}`
        };
      }
      if (this.state.countryCodeWhitelist !== void 0 && !this.state.countryCodeWhitelist.includes(countryCode)) {
        return {
          errorCode: import_general_commissioning.GeneralCommissioning.CommissioningError.ValueOutsideRange,
          debugText: `Country code change not allowed: ${countryCode}`
        };
      }
      if (countryCode !== "XX") {
        basicInformation.state.location = countryCode;
      }
    }
    let validValues;
    switch (locationCapabilityValue) {
      case import_general_commissioning.GeneralCommissioning.RegulatoryLocationType.Outdoor:
        validValues = [import_general_commissioning.GeneralCommissioning.RegulatoryLocationType.Outdoor];
        break;
      case import_general_commissioning.GeneralCommissioning.RegulatoryLocationType.Indoor:
        validValues = [import_general_commissioning.GeneralCommissioning.RegulatoryLocationType.Indoor];
        break;
      case import_general_commissioning.GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor:
        validValues = [
          import_general_commissioning.GeneralCommissioning.RegulatoryLocationType.Indoor,
          import_general_commissioning.GeneralCommissioning.RegulatoryLocationType.Outdoor,
          import_general_commissioning.GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor
        ];
        break;
      default:
        return {
          errorCode: import_general_commissioning.GeneralCommissioning.CommissioningError.ValueOutsideRange,
          debugText: `Invalid regulatory location: ${newRegulatoryConfig === import_general_commissioning.GeneralCommissioning.RegulatoryLocationType.Indoor ? "Indoor" : "Outdoor"}`
        };
    }
    if (!validValues.includes(newRegulatoryConfig)) {
      return {
        errorCode: import_general_commissioning.GeneralCommissioning.CommissioningError.ValueOutsideRange,
        debugText: `Invalid regulatory location: ${newRegulatoryConfig === import_general_commissioning.GeneralCommissioning.RegulatoryLocationType.Indoor ? "Indoor" : "Outdoor"}`
      };
    }
    this.state.regulatoryConfig = newRegulatoryConfig;
    this.state.breadcrumb = breadcrumb;
    return SuccessResponse;
  }
  async commissioningComplete() {
    (0, import_protocol.assertRemoteActor)(this.context);
    const { session } = this.context;
    if (import_protocol.NodeSession.is(session) && session.isPase || import_protocol.GroupSession.is(session)) {
      return {
        errorCode: import_general_commissioning.GeneralCommissioning.CommissioningError.InvalidAuthentication,
        debugText: "Command must be executed over CASE session."
      };
    }
    const fabric = session.associatedFabric;
    const commissioner = this.env.get(import_protocol.DeviceCommissioner);
    if (!commissioner.isFailsafeArmed) {
      return { errorCode: import_general_commissioning.GeneralCommissioning.CommissioningError.NoFailSafe, debugText: "FailSafe not armed." };
    }
    const failsafeContext = commissioner.failsafeContext;
    import_protocol.SecureSession.assert(session, "Commissioning may only complete on a secure session");
    const timedFabric = failsafeContext.associatedFabric?.fabricIndex;
    if (fabric.fabricIndex !== timedFabric) {
      return {
        errorCode: import_general_commissioning.GeneralCommissioning.CommissioningError.InvalidAuthentication,
        debugText: `Associated fabric index ${fabric.fabricIndex} does not match failsafe fabric index ${timedFabric}`
      };
    }
    await failsafeContext.completeCommission();
    this.state.breadcrumb = BigInt(0);
    logger.info(
      "Commissioned",
      import_general.Diagnostic.dict({
        fabric: `${import_general.hex.fixed(fabric.globalId, 16)} (#${fabric.fabricIndex})`,
        node: import_general.hex.fixed(fabric.nodeId, 16)
      })
    );
    return SuccessResponse;
  }
}
((GeneralCommissioningServer2) => {
  class State extends import_GeneralCommissioningBehavior.GeneralCommissioningBehavior.State {
    /**
     * Set to false to prevent the controller from changing the country code during commissioning.
     */
    allowCountryCodeChange = true;
    // Default true if not set
    /**
     * Set to an array of two-letter country codes to limit the countries the controller may assign.
     */
    countryCodeWhitelist = void 0;
  }
  GeneralCommissioningServer2.State = State;
})(GeneralCommissioningServer || (GeneralCommissioningServer = {}));
//# sourceMappingURL=GeneralCommissioningServer.js.map
