/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
import { Privilege, aclEntryKey, attributeArray, entriesForFabric } from "../../../util/access-control.js";
import { AccessControlEntryDataTransformer } from "./model.js";
function toApiAcl(e) {
  return {
    privilege: e.privilege,
    auth_mode: e.authMode,
    subjects: e.subjects ?? null,
    targets: e.targets?.map((t) => ({
      cluster: t.cluster ?? null,
      endpoint: t.endpoint ?? null,
      device_type: t.deviceType ?? null
    })) ?? null
  };
}
async function freshOurAcl(client, nodeId) {
  const res = await client.readAttribute(nodeId, ["0/31/0", "0/62/5"]);
  const all = attributeArray(res["0/31/0"]).map((v) => AccessControlEntryDataTransformer.transform(v));
  const fi = res["0/62/5"];
  if (typeof fi !== "number") {
    throw new Error(`Cannot determine the current fabric index (0/62/5) for node ${nodeId}`);
  }
  return entriesForFabric(all, fi);
}
async function addAclEntry(client, nodeId, entry) {
  const acl = await freshOurAcl(client, nodeId);
  acl.push(entry);
  await client.setACLEntry(nodeId, acl.map(toApiAcl));
}
async function deleteAclEntry(client, nodeId, key) {
  const acl = await freshOurAcl(client, nodeId);
  let removed = false;
  const kept = acl.filter((e) => {
    if (!removed && aclEntryKey(e) === key) {
      removed = true;
      return false;
    }
    return true;
  });
  await client.setACLEntry(nodeId, kept.map(toApiAcl));
}
async function downgradeToOperate(client, nodeId, keys) {
  const acl = await freshOurAcl(client, nodeId);
  const updated = acl.map((e) => keys.has(aclEntryKey(e)) ? { ...e, privilege: Privilege.Operate } : e);
  await client.setACLEntry(nodeId, updated.map(toApiAcl));
}
export {
  addAclEntry,
  deleteAclEntry,
  downgradeToOperate
};
//# sourceMappingURL=acl-actions.js.map
