import {
  forbidden,
  notFound
} from "./chunk-EZYKRG4W.js";

// src/auth/scope.ts
function requireAdmin(auth) {
  if (!auth.permissions.admin) {
    throw forbidden("admin permission required");
  }
}
function requireGlobalAdmin(auth) {
  if (!auth.isGlobalAdmin) {
    throw forbidden("global admin permission required");
  }
}
function effectiveTenant(auth) {
  if (auth.actingAsTenant) return auth.actingAsTenant;
  return auth.tenantId;
}
function tenantFilter(auth) {
  if (auth.actingAsTenant) return auth.actingAsTenant;
  if (auth.isGlobalAdmin) return null;
  return auth.tenantId;
}
function assertResourceTenant(auth, resourceTenantId, notFoundMsg) {
  const acting = effectiveTenant(auth);
  if (acting !== null) {
    if (resourceTenantId === acting) return;
    throw notFound(notFoundMsg);
  }
  if (auth.isGlobalAdmin) return;
  throw notFound(notFoundMsg);
}
function resolveCreateTenant(auth, bodyTenantId) {
  if (auth.actingAsTenant) return auth.actingAsTenant;
  if (auth.isGlobalAdmin) {
    if (bodyTenantId) return bodyTenantId;
    if (process.env.REQUIRE_TENANT_HEADER === "1") {
      throw forbidden(
        "global-admin requests must declare a tenant via the `x-agentstep-tenant` header or `tenant_id` field. The legacy tenant_default fallback is disabled when REQUIRE_TENANT_HEADER=1 (PR6 / agent-sdk 0.5.58+)."
      );
    }
    return "tenant_default";
  }
  if (!auth.tenantId) {
    throw forbidden("this key has no tenant assigned");
  }
  return auth.tenantId;
}
function allowed(list, id) {
  return list.includes("*") || list.includes(id);
}
function checkResourceScope(auth, resources) {
  const { scope } = auth.permissions;
  if (scope === null) return;
  if (resources.agent != null && !allowed(scope.agents, resources.agent)) {
    throw forbidden(`api key scope does not include agent ${resources.agent}`);
  }
  if (resources.env != null && !allowed(scope.environments, resources.env)) {
    throw forbidden(`api key scope does not include environment ${resources.env}`);
  }
  if (resources.vaults && resources.vaults.length > 0) {
    for (const vid of resources.vaults) {
      if (!allowed(scope.vaults, vid)) {
        throw forbidden(`api key scope does not include vault ${vid}`);
      }
    }
  }
}

export {
  requireAdmin,
  requireGlobalAdmin,
  effectiveTenant,
  tenantFilter,
  assertResourceTenant,
  resolveCreateTenant,
  checkResourceScope
};
