function normalizeScopeValue(value) {
  if (typeof value !== "string") return null;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : null;
}
function assertAttachmentScopeInvariant(scope) {
  const tenantId = normalizeScopeValue(scope.tenantId);
  const organizationId = normalizeScopeValue(scope.organizationId);
  const tenantSet = tenantId !== null;
  const organizationSet = organizationId !== null;
  if (tenantSet !== organizationSet) {
    const missing = tenantSet ? "organization_id" : "tenant_id";
    throw new Error(
      `[internal] Attachment scope invariant violated: ${missing} is null while the other scope column is set. Attachments must be either fully scoped (both tenant_id and organization_id) or fully global (both null).`
    );
  }
}
function isSuperAdminAuth(auth) {
  if (!auth) return false;
  if (auth.isSuperAdmin === true) return true;
  const roles = Array.isArray(auth.roles) ? auth.roles : [];
  return roles.some((role) => typeof role === "string" && role.trim().toLowerCase() === "superadmin");
}
function isSameScope(auth, attachment) {
  if (!auth) return false;
  const attachmentTenant = attachment.tenantId ?? null;
  const attachmentOrg = attachment.organizationId ?? null;
  if (attachmentTenant === null && attachmentOrg === null) {
    return true;
  }
  return attachmentTenant === auth.tenantId && attachmentOrg === auth.orgId;
}
function checkAttachmentAccess(auth, attachment, partition, options) {
  const superAdmin = isSuperAdminAuth(auth);
  const requireAuth = !partition.isPublic || options?.requireAuthForPublic === true;
  if (requireAuth) {
    if (!auth) {
      return { ok: false, status: 401 };
    }
    if (superAdmin || isSameScope(auth, attachment)) {
      return { ok: true };
    }
    return { ok: false, status: 403 };
  }
  if (!auth) {
    const isTenantScoped = !!attachment.tenantId || !!attachment.organizationId;
    if (isTenantScoped) {
      return { ok: false, status: 401 };
    }
    return { ok: true };
  }
  if (!superAdmin && !isSameScope(auth, attachment)) {
    return { ok: false, status: 403 };
  }
  return { ok: true };
}
export {
  assertAttachmentScopeInvariant,
  checkAttachmentAccess,
  isSuperAdminAuth
};
//# sourceMappingURL=access.js.map
